Check out this Angular service method that calls a basic 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 Interface:
export interface Token {
some_val:String;
some_val2:String;
some_val3:String;
}
Snippet of code from the component invoking 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)
}
}
Upon console logging, the output displays an issue as follows:
obj :undefined
ERROR TypeError: Cannot read properties of undefined (reading 'some_val')
This HTML tag effectively shows the JSON object (token) on the user interface:
<pre>{{token | json}}</pre>
However, to access fields from the token object within the component class without displaying them on the UI, consider setting certain fields to browser cookies.