在我的Angular应用程序中,我建立了一个服务,它从MongoDB中获取一些数据作为json-Array。这是我服务的代码:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';
@Injectable()
export class IdeaServiceService {
private _getURL = '/api/1.0.0/ideas';
constructor(private _http: HttpClient) { }
getIdeas() {
return this._http.get(this._getURL).map((response: Response) => response.json());
}
}
在另一个组件中,我尝试订阅此服务并将获取的数据存储到Idea数组中(我建立的各个类)。这是相应的代码:
import { Component, OnInit } from '@angular/core';
import {Idea} from '../idea';
import {IdeaServiceService} from '../idea-service.service';
@Component({
selector: 'app-ideas-overview',
templateUrl: './ideas-overview.component.html',
styleUrls: ['./ideas-overview.component.css'],
providers: [IdeaServiceService]
})
export class IdeasOverviewComponent implements OnInit {
ideas: Array<Idea>;
constructor(private _ideaService: IdeaServiceService) { }
ngOnInit() {
this._ideaService.getIdeas().subscribe(resIdeaData => this.ideas = resIdeaData);
}
}
现在出现以下类型错误:
错误:(19,59)TS2322:输入&#39;承诺&#39;不能分配给类型&#39; Idea []&#39;。 财产包括&#39;类型&#39;承诺&#39;
中缺少非常感谢您的支持!
答案 0 :(得分:0)
response.json()在等待时返回Promise而不是plain数组。所以你必须另外使用then():
ngOnInit() {
this._ideaService.getIdeas().subscribe(jsonPromise => {
jsonPromise.then(resIdeaData => {
this.ideas = resIdeaData;
});
});
}