최근에 Angular를 사용하여 DB에서 일부 리소스를 가져 와서 정렬하고 표시하는 간단한 작업을 수행하기 시작했습니다.Angular 2 Service Observable returns undefined
그러나 구성 요소는 undefined를 받고 정렬 할 수 없습니다. 나는이 질문이 여러 번 부탁 받았지만 제시된 해결책이 도움이되지 않았기 때문에 나에게 들려주세요.
나는 다음과 같은 스레드
angular2 services returns undefined
angular2 observable, getting undefined in component
내 필요에 따라 angular.io 구글의 튜토리얼을 시작하고 확장/코드를 수정
angular2 observable, getting undefined in component
살펴 보았다및 followi 시도 NG :
서비스 :
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
또한 시도 : 구성 요소
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[]})
다른 스레드
제안 로서도 getAlbums()의 본체 내부에 다음과 같은 3 시도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);
}
다음 구성 요소에서 :
,451,515,
this.albumService.getAlbums()
.subscribe(result => this.albums = result.sort((function(a,b){
return (a.artist > b.artist) ? 1 : ((b.artist > a.artist) ? -1 : 0);
})))
나는
가 정의되지 않은
의 속성 종류를 읽을 수 없습니다 다음과 같은 오류가 발생하고 어떤 이유로 약속하기 전에 서비스 리턴 해결한다는 결론을 내렸다하지만 잘못 될 수도 주목해야 할 중요한 점은 위의 서비스 코드에서 console.log (응답)가 서버의 올바른 응답을 출력한다는 것입니다. 따라서 데이터가 올바른 각도 서비스에 도달하지만 서비스와 구성 요소간에 무언가가 발생합니다.
도움이 되었습니까? 서비스 내부에 캐스팅
@Sajaeetharan이 감사에 액세스 할 수 없습니다! 아직 작업에 대한 정확한 응답을 얻을 수 없지만 .map 케이스에서 캐스팅을 제거하면 작동합니다. 캐스팅이 왜 중단되는지에 대해 좀 더 자세히 설명해 주시겠습니까? 그것은 실패하거나 뭔가를 빈 인스턴스를 반환합니까? – sinanspd