通常情况下,我们在Angular中使用HTTP服务发送HTTP请求并返回响应。 HTTP服务通过依赖注入的形式添加到组件/服务中。
但有时,当我们从组件中调用HTTP请求时,它不会返回任何内容。这是因为HTTP请求是异步的,如果我们尝试在没有等待响应的情况下返回响应,则可能会出现此问题。
要解决此问题,您可以使用Observable来处理HTTP响应。以下是一个示例代码:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient) { }
getData(): Observable {
return this.http.get('https://jsonplaceholder.typicode.com/posts');
}
}
在上面的代码中,我们使用rxjs的Observable对象来处理HTTP响应。现在,我们可以从组件中订阅这个函数并得到响应。
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'my-app';
data: any;
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData()
.subscribe((response) => {
this.data = response;
});
}
}
在这个组件中,我们订阅了dataService中的getData函数并在订阅的响应中接收数据。现在,您应该能够正确地接收HTTP响应并解决问题。
上一篇:Angular服务和组件