[英]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.