出现以下错误:类型'Promise'不能分配给类型'string []'。类型“ Promise”中缺少属性“ includes”。
当我将Promise强制键入“ string []”下面的代码时,
组件:app.dashboard.ts
import {Component} from '@angular/core';
import { MemberService } from "./app.service";
@Component({
selector:'app-root',
templateUrl:'./app.dashboard.html',
providers:[MemberService]
})
export class AppDashboard{
title='Dashboard'
constructor(private memberService: MemberService) { }
public doughnutChartLabels:string[] =
this.memberService.getmemberheader();//error occurred here
}
}
服务:app.service.ts
import { Injectable } from '@angular/core';
import { Member } from './Member';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from'@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class MemberService
{
constructor(private http: Http) {
}
private getHeaders(){
// I included these headers because otherwise FireFox
// will request text/html instead of application/json
let headers = new Headers();
headers.append('Accept', 'application/json');
return headers;
}
getmemberheader(): Promise<string[]> {
return this.http
.get(`/ReportService/MemberDatabaseCountryname`, {headers: this.getHeaders()})
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
假设您的响应来自http.get
一个数组,这里您Promise
要从function返回memberService.getmemberheader
,您应该then
改为在其回调中获取promise的结果(而不是将promise本身分配给array doughnutChartLabels
)。
public doughnutChartLabels: string[];
this.memberService.getmemberheader().then(res => {
this.doughnutChartLabels = res;
})
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句