简体   繁体   中英

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.

However the component receives undefined and can not sort.

I have looked at the following threads

angular2 observable, getting undefined in component

angular2 services returns undefined

angular2 observable, getting undefined in component

I started off Google's tutorial at angular.io and expanded/modified the code according to my needs

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

  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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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