Angular 2 Service Observable Returns undefined

问题描述:

我最近开始玩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(响应),打印出服务器的正确响应。所以数据确实达到了正确的角度服务,但服务和组件之间发生了一些事情

任何帮助表示赞赏!

删除里面的服务铸造,当它失败,你将无法访问

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

@Sajaeetharan谢谢!我无法得到确切的响应,但是如果我从.map案例中删除了投射,它就可以工作。 你能否给出一些关于为什么要打破这个的更多细节?当它失败或返回一个空的实例时它会返回吗? – sinanspd