[英]Why angular Service data is get undefined if I call from component
我正在使用 JSONPlace holder Fake API 来获取数据。 我正在获取服务中的 api 数据,但是如果我从我的应用程序组件调用该服务,我将undefined
为什么这是我的代码
我的 Service.ts 是
import { Injectable } from '@angular/core';
import { Http, URLSearchParams, Response, RequestOptions, Headers } from '@angular/http';
import 'rxjs/RX';
import 'rxjs/add/operator/map';
@Injectable()
export class Service {
apiRoot: string = 'https://jsonplaceholder.typicode.com/comments?'
postId = 1;
data;
constructor(private _http: Http) {
this._http.get(this.apiRoot).subscribe((data) => {
this.data = data.json();
});
}
init() {
return this.data;
}
}
我的组件代码是
import { Component, OnInit } from '@angular/core'; import { InfiniteService } from './infinite.service'; //import all rxjs/Rx opeartor import 'rxjs/add/operator/map';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit {
data;
constructor(private _infinteService: InfiniteService) {
this.data = this._infinteService.init();
console.log(this.data);
}
GetPosition($event) {
if ($event == 'Bottom') {
console.log($event);
}
else {
console.log($event);
}
}
ngOnInit() { }
}
为什么我无法在组件中获取服务数据?
因为 HTTP 它的异步功能! 我推荐使用HttpClient,所以你不需要使用map
函数! 你可以试试
getData(): Observable<any> {
return this._http.get(this.apiRoot)
}
你就这样在组件中调用他
this._infinteService.getData().subscribe(
data => console.log(data)
)
您需要返回一个 Observable,然后您可以使用 subscribe 来调用请求。 试试看,看看是否有效! 谢谢
在您的代码中进行以下更改。
服务 :
constructor(private _http: Http) {
}
init() {
return this._http.get(this.apiRoot);
}
成分 :
constructor(private _infinteService: InfiniteService) {
this._infinteService.init().subscribe((data) => {
this.data = data;
console.log(this.data);
});
}
您需要在组件调用中使用.subscribe
。
您不需要数据对象上的.json()
。 从 Angular4 开始,默认的 responseType 是 JSON,并且已经为我们解析了响应数据。
您应该从您的服务返回Observable
并在您的组件中订阅它。
发生这种情况的原因是需要一些时间才能从服务器获得响应。 所以我们可以在promise中设置它。 使用以下命令获取 promise 中的数据。
this._customerService.getCustomers().subscribe(data => this.customers = data);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.