首页 文章

Angular 2 Service Observable返回undefined

提问于
浏览
0

我最近开始玩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 回答

  • 3

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

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

相关问题