[英]Angular 2 Service Observable returns undefined
我最近開始與Angular一起玩耍,嘗試完成一個簡單的任務,即從數據庫中獲取一些資源,對其進行排序並顯示它們。
但是,組件收到未定義的內容,無法排序。
我看過以下主題
我從angular.io開始了谷歌的教程,並根據需要擴展/修改了代碼
並嘗試了以下方法:
服務:
import { Album } from './album';
import { ALBUMS } from './mock-albums';
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
@Injectable()
export class AlbumService {
private albumURL = '/api/albums';
constructor (private http: Http) { }
getAlbums(): Promise<Album[]> {
return this.http.get(this.albumURL)
.toPromise()
.then(response => {response.json().data as Album[];
console.log(response)})
.catch(this.handleError);
}
還嘗試了其他線程建議的在getAlbums()主體內的以下3個
return this.http.get(this.albumURL)
.map(response => response.json().data as Album[])
.toPromise();
return this.http.get(this.albumURL)
.map(response => {response.json().data as Album[])
return this.http.get(this.albumURL)
.map(response => { return response.json().data as Album[]})
零件:
import { Component, OnInit } from '@angular/core';
import { Album } from './album';
import { AlbumService } from './album.service';
import { Subscription } from 'rxjs/Rx';
@Component({
selector: 'album-dashboard',
templateUrl: 'dashboard.component.html',
styleUrls: [ 'dashboard.component.css' ]
})
export class DashboardComponent implements OnInit {
albums: Album[] = [];
constructor(private albumService: AlbumService) { };
ngOnInit(): void {
this.albumService.getAlbums()
.then(result => this.albums = result.sort((function(a,b){
return (a.artist > b.artist) ? 1 : ((b.artist > a.artist) ? -1 : 0);
})))
}
.... the rest of the class continues
在組件中還嘗試了以下操作:
this.albumService.getAlbums()
.subscribe(result => this.albums = result.sort((function(a,b){
return (a.artist > b.artist) ? 1 : ((b.artist > a.artist) ? -1 : 0);
})))
我收到以下錯誤,並得出結論:由於某種原因,服務在Promise解決之前就返回了,但我可能錯了
無法讀取未定義的屬性
需要注意的重要一點是,上面服務代碼上的console.log(response)會打印出服務器的正確響應。 因此,數據確實到達了正確的角度服務,但是服務和組件之間發生了某些情況
刪除服務內部的強制轉換,當服務失敗時,您將無法訪問
return this.http.get(this.albumURL)
.toPromise()
.then(response => {response.json();
console.log(response)})
.catch(this.handleError);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.