Angular 2 Service Observable返回undefined

时间:2017-10-22 01:43:17

标签: angular typescript

我最近开始玩Angular并试图完成从DB获取一些资源,对它们进行排序并显示它们的简单任务。

但是组件接收未定义且无法排序。

我查看了以下主题

angular2 observable, getting undefined in component

angular2 services returns undefined

angular2 observable, getting undefined in component

我在angular.io开始了Google的教程,并根据我的需要扩展/修改了代码

并尝试了以下内容:

服务:

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结算之前返回但我可能错了

无法读取属性类型的未定义

enter image description here

需要注意的一点是,上面服务代码上的console.log(响应)会打印出来自服务器的正确响应。因此,数据确实达到了正确的角度服务,但服务和组件之间发生了一些事情

1 个答案:

答案 0 :(得分:3)

删除服务内部的转换,当它失败时,您将无法访问

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