0

Here is the method from my Angular service calling a simple REST API:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Token } from './Token';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class TokenServiceService {

  constructor(private http: HttpClient) { }

  public getToken(code:any):Observable<Token> {

    const url = 'http://example.com/token?code='+ code +'&state=STATE123';
    
    return this.http.get<Token>(url);
  }
}

Token:

export interface Token {
  some_val:String;
  some_val2:String;
  some_val3:String;
}

Here is the code snippet from the component that calls the above method:

import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Token } from '../Token';
import { TokenServiceService } from '../token-service.service';
import { GlobalComponent } from '../global-component'


@Component({
  selector: 'app-accesstoken',
  templateUrl: './accesstoken.component.html',
  styleUrls: ['./accesstoken.component.css']
})
export class AccesstokenComponent implements OnInit {

  public token!:Token;
 
  constructor(private route: ActivatedRoute, private tokenService: TokenServiceService) {}

  ngOnInit(): void {

    const code = this.route.snapshot.queryParamMap.get('code');

    this.tokenService.getToken(code).subscribe(data => this.token = data)
    console.log('obj : '+this.token)
    console.log(this.token.some_val)
  }
}

Console output [here is the problem]:

obj :undefined
ERROR TypeError: Cannot read properties of undefined (reading 'some_val')

This tag in html successfully displays Json object (token) on UI:

<pre>{{token | json}}</pre>

But how can I access fields from token obj in my component class itself without displaying on GUI? I Want to set some fields to a browser cookies.

1 Answer 1

1

My guess is that the problem is with the asynchronous nature of .subscribe() and Observables in general. In AccesstokenComponent your console.log lines are going to be called before the this.token = data assignment, which has to wait for the observable to get resolved. Calling the subscribe method doesn't make your code to wait for the execution of that observable, instead you can register the callback that's going to be invoked once the observable is ready. I bet if you put those logs inside the subscribe callback, after the assignment, you'd be able to see the contents of this.token.

EDIT: You also want to render this token value in the template. For this purpose I'd recommend getting familiar with the async pipe (basically if you make your field an Observable<something>, then you've got to call it in the template with | async to render it)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.