Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erro: Type 'string' is not assignable to type '"body"'. in angular 8

ERROR in src/app/new-applicant/new-applicant.service.ts(35,65): error TS2345: Argument of type '{ reportProgress: boolean; observe: string; headers: HttpHeaders; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; }; observe?: "body"; params?: HttpParams | { [param: string]: string | string[]; }; reportProgress?: boolean; responseType?: "json"; withCredentials?: boolean; }'. Types of property 'observe' are incompatible. Type 'string' is not assignable to type '"body"'.

    public generateHeaders()
    {
        let access=JSON.parse(sessionStorage.getItem("meta_info")).access
        // access=access.access;
        console.log(access)
        var headers_object = new HttpHeaders().set("Authorization", "Bearer " + access);
        const httpOptions = {
            reportProgress:true,
            observe:'events',
            headers: headers_object
        };
        return httpOptions
    }

service

  public registerNewApplicant(data)
  {
    return this.http.post(environment.baseURL+"applicant/",data,this.jwtTokenGenerator.generateHeaders())
  }
like image 778
NrJ Avatar asked Jan 25 '23 07:01

NrJ


2 Answers

Use as const to force TypeScript to infer the type of observe as the literal type "events" instead of string:

observe: 'events' as const,

Each method in HttpClient has a bunch of overloads which expect observe to be one of the following: "body", "events", "response".

TypeScript by default infers type of string literals as string, except in some contexts such as initializing a const or readonly fields. The return type of generateHeaders ends up being

{ reportProgress: boolean; observe: string; headers: HttpHeaders; }

The info about observe being "events" is lost, so this value does not match any of the overloads.

like image 103
p4m Avatar answered Jan 28 '23 09:01

p4m


Cast it to 'events'

observe: 'events' as 'events'
like image 30
Mohammad Awwaad Avatar answered Jan 28 '23 10:01

Mohammad Awwaad