2017-10-22 130 views
0

我最近開始玩Angular,試圖完成從數據庫獲取一些資源,排序並顯示它們的簡單任務。Angular 2 Service Observable Returns undefined

但是,組件接收到未定義的,無法排序。我知道這個問題已經被問過很多次了,但是由於提出的解決方案沒有幫助,所以請放棄我。

我已經看過下面的線程

angular2 observable, getting undefined in component

angular2 services returns undefined

angular2 observable, getting undefined in component

我開始了谷歌的教程在angular.io和擴展/修改了代碼,根據我的需求

並嘗試了以下NG:

服務:

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); 
    } 

另外嘗試了以下3 getAlbums()的主體內由其他線程

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); 
}))) 

我碰到下面的錯誤,並已得出結論,由於某種原因,無極前的服務回報解決了,但我可能是錯的

無法讀取屬性之類的不確定

enter image description here

的重要的是要注意的是,上面的服務代碼的console.log(響應),打印出服務器的正確響應。所以數據確實達到了正確的角度服務,但服務和組件之間發生了一些事情

任何幫助表示讚賞!

回答

3

刪除裏面的服務鑄造,當它失敗,你將無法訪問

return this.http.get(this.albumURL) 
      .toPromise() 
      .then(response => {response.json(); 
        console.log(response)}) 
      .catch(this.handleError); 
    } 
+0

@Sajaeetharan謝謝!我無法得到確切的響應,但是如果我從.map案例中刪除了投射,它就可以工作。 你能否給出一些關於爲什麼要打破這個的更多細節?當它失敗或返回一個空的實例時它會返回嗎? – sinanspd