这是由于接收到的响应尚未完全解析而导致的。我们可以使用rxjs中的map操作符对响应进行转换,然后在组件中订阅转换后的数据。以下是解决方案的代码示例:
在服务中:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map';
@Injectable() export class MyService { constructor(private http: HttpClient) {}
getData(): Observable
在组件中:
import { Component, OnInit } from '@angular/core'; import { MyService } from './my.service';
@Component({
selector: 'app-my-component',
template:
,
})
export class MyComponent implements OnInit {
myData: any[];
constructor(private myService: MyService) {}
ngOnInit() { this.myService.getData().subscribe( response => this.myData = response, error => console.error(error) ); } }
以上代码示例展示了如何正确地从url获取数据,并将其显示在组件中。请注意,在服务中使用.map()操作符转换响应,以便其可以轻松地呈现在组件中。在组件中,我们订阅转换后的数据来获得要显示的结果。
上一篇:AngularHTTPGet请求-ERRORError:Uncaught(inpromise):
下一篇:AngularHttpInterceptor-fromPromiseerror-TypeError:(0,x.fromPromise)isnotafunction