POST Method in Angular

2

I have a simple application in Angular and I need to call my API to get a token . But I am facing difficulties. I'll try to explain a bit about my flow.

I created a service class where I instantiate it only once to store a Token. This token comes from an API, but this API does not return me a token on every call because this token has a life time of 15min. When the API returns me a token, it comes in this format:

{access_token: "32-GaypcnKItxyYBhc9HRINLebbzuoWul9q0zNitHq0ZVIcVGB…AV2LoFg3uoY6xNIMExkKEbGyda_5Z0RXFnKdi6UsBPH5b-Lwa", token_type: "bearer", expires_in: 3599}

If it comes in this format, my intention is to get this token received by the API and store it within my class said above.

If the API does not return a Token, the response comes in this format:

Response {_body: "{"error":"deny","error_description":"permitido som… autenticação por aplicação à cada 15 minuto(s)"}", status: 400, ok: false, statusText: "Bad Request", headers: Headers, …}

Informing by _body, an error described: 'allowed sound ... authentication per application every 15 minute (s)'.

If it comes in this format, my intention is to enter the class that instantiated the start and get the token that is in the class said above.

When the API returns a Token, I can get it. But when it does not return a Token, I can not get the token that is stored in the class.

Could someone please help me? Below the attempts code

Class of service

 ObterToken(): Observable<any> {
  const header = new Headers();
  header.append('Content-Type', 'application/x-www-form-urlencoded');
  const bodyOptions = { 
      grant_type: 'password',
      username: 'varejo_user', 
      password: 'w6h5xgtl'
  }
  const body = 'grant_type=${bodyOptions.grant_type}&username=${bodyOptions.username}&password=${bodyOptions.password}';

  return this.http.post('${ApiDeSegurança}', body, new RequestOptions({headers: header}))
      .map(response=> response.json());
}

ObtendoToken(): string {
  return this.tokenModel.token;
}

AdicionandoToken(token: string): void {
  this.tokenModel.token = token;
}

Component that implements the class of service

ngOnInit(): void {
    this.apiDeSegurancaService.ObterToken().subscribe(res => this.token = res);
}

Edited question

It worked this way:

  ngOnInit(): void { 
    this.apiDeSegurancaService.ObterToken().subscribe( res => { 
            this.apiDeSegurancaService.AdicionandoToken(res.access_token);
        }, error => { 
            this.token = this.apiDeSegurancaService.ObtendoToken();
        });
}

However, I need to perform another method with this token, so I need to perform this other method only when that first request has a response! How can I do this?

Thank you in advance.

    
asked by anonymous 11.06.2018 / 13:46

1 answer

1

You can receive error handling by adding a response string.

ngOnInit(): void { 
   this.apiDeSegurancaService.ObterToken().subscribe(
    res => { 
       this.token = res 
    }, error => {
       this.error = error 
   }); 
} 
    
11.06.2018 / 19:26