简体   繁体   English

Angular 2 Service Observable返回未定义

[英]Angular 2 Service Observable returns undefined

I recently started playing around with Angular and trying to achieve the simple task of getting some resources from a DB, sorting them and displaying them. 我最近开始与Angular一起玩耍,尝试完成一个简单的任务,即从数据库中获取一些资源,对其进行排序并显示它们。

However the component receives undefined and can not sort. 但是,组件收到未定义的内容,无法排序。

I have looked at the following threads 我看过以下主题

angular2 observable, getting undefined in component angular2可观察到,在组件中变得不确定

angular2 services returns undefined angular2服务返回未定义

angular2 observable, getting undefined in component angular2可观察到,在组件中变得不确定

I started off Google's tutorial at angular.io and expanded/modified the code according to my needs 我从angular.io开始了谷歌的教程,并根据需要扩展/修改了代码

and tried the following: 并尝试了以下方法:

Service: 服务:

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

Also tried the following 3 inside the body of getAlbums() as suggested by other threads 还尝试了其他线程建议的在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[]}) 

Component: 零件:

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

Also tried the following in the component: 在组件中还尝试了以下操作:

this.albumService.getAlbums()
   .subscribe(result => this.albums = result.sort((function(a,b){
    return (a.artist > b.artist) ? 1 : ((b.artist > a.artist) ? -1 : 0);
})))

I get the following error and have concluded that for some reason the service returns before the Promise resolves but I might be wrong 我收到以下错误,并得出结论:由于某种原因,服务在Promise解决之前就返回了,但我可能错了

Can not read property sort of undefined 无法读取未定义的属性

在此处输入图片说明

An important thing to note is that console.log(response) on the service code above, prints out the correct response from the server. 需要注意的重要一点是,上面服务代码上的console.log(response)会打印出服务器的正确响应。 So the data does reach the correct angular service but something happens between the service and component 因此,数据确实到达了正确的角度服务,但是服务和组件之间发生了某些情况

Remove casting inside the service, when it fails you will not be able to access 删除服务内部的强制转换,当服务失败时,您将无法访问

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM