输入"Promise< string []>"不可分配给'string []'类型 [英] Type 'Promise<string[]>' is not assignable to type 'string[]'

查看:187
本文介绍了输入"Promise< string []>"不可分配给'string []'类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出现以下错误: 类型'Promise'不能分配给类型'string []'. 类型"Promise"中缺少属性"includes".

Getting following error: Type 'Promise' is not assignable to type 'string[]'. Property 'includes' is missing in type 'Promise'.

当我将Promise键入"string []"时 我的下面的代码,

when i cast Promise to type 'string[]' My code below,

组件: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
  }
}

Service: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的响应是一个数组,此处您要从函数memberService.getmemberheader返回Promise,则应在其then回调(而不是将诺言本身分配给数组doughnutChartLabels).

Assume your response from http.get is an array, here you are returning Promise from function memberService.getmemberheader, you should retrieve result of promise at its then callback instead (not assigning promise itself to array doughnutChartLabels).

public doughnutChartLabels: string[];

this.memberService.getmemberheader().then(res => {
  this.doughnutChartLabels = res;
})

这篇关于输入"Promise&lt; string []&gt;"不可分配给'string []'类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆