Type 'Promise<string[]>' is not assignable to type 'string[]'

Viewed 82667

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

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

Component: 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);
      }
    }
2 Answers

@levolutionniste

The function getmemberheader() returns a promise.

The main motivation for promises is to bring synchronous style error handling to Async / Callback style code. ES6 has adopted this spec for its Promise implementation. Promises have a special syntax that allows promises to be daisy-chained together, allowing the results from one promise to feed the next promise.

So:

getmemberheader()
.then((returnsAStringArrayObjectHere_YouCanCallItAnythingYouLike) => {
 // Do something with this array here
})
.catch((error) => {
 console.log("Oops something went wrong: ", error);
});

Here are some articles on promises:

So getmemberheader will return a promise of type string[].

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

This is why on the middle line the variable res contains the string[] from getmemberhead promise. Then in the code block {} the user sets a field doughnutChartLabels to this variable res.

Promises are great to use especially when working with ORM's which often return promises, making it easy to daisy-chain them together - which ensures that the code runs synchronously from left to right throughout the promise chain.

Related