Navigating through JSON object fields within Angular component [Version 11]

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.

Answer №1

I suspect that the issue lies in the asynchronous nature of .subscribe() and Observables as a whole. In the AccesstokenComponent, your console.log statements will be executed prior to the this.token = data assignment, which requires the observable to be resolved first. When you call the subscribe method, it does not halt the code execution for the completion of the observable; instead, you can specify a callback function that will only run once the observable is ready. If you move those logs inside the subscribe callback, subsequent to the assignment, you should be able to view the contents of this.token.

EDIT: Furthermore, you may need to display this token value in the template. In such cases, I suggest familiarizing yourself with the async pipe (essentially, if you define your field as an Observable<something>, then you must use | async in the template to render it)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmit information from an IONIC 3 application to a PHP server using the POST method

Having trouble sending data from Ionic 3 to php via the http library using post? When php tries to retrieve it, it's unable to locate. Below is the Typescript file that generates the token to be sent to php and calls the php file on localhost (xampp) ...

Having trouble obtaining search parameters in page.tsx with Next.js 13

Currently, I am in the process of developing a Next.js project with the Next 13 page router. I am facing an issue where I need to access the search parameters from the server component. export default async function Home({ params, searchParams, }: { ...

Understanding the concept of inconsistent return points in Typescript: What implications does it carry?

I am currently working on converting a NodeJs JavaScript code to TypeScript. The code snippet below shows how I save uploaded files using JavaScript and now I'm encountering an error when trying to do the same in TypeScript. The error message says "Fu ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

Ways to boost the efficiency of your Ionic 4 app development process

I have created an Ionic 4 app with over 50 screens, including components and popups. The build and live reload process is taking a lot of time, especially for minor UI changes. Is there a way to speed up the development process? Here are my Environment Se ...

Tips for refreshing the current Angular 2 Component

I'm looking for a way to refresh the same component in Angular 2. Can anyone provide guidance? Below is the code snippet I have: import { Component, OnInit, ElementRef, Renderer } from '@angular/core'; import { Router, ActivatedRoute, Para ...

What is the importance of typescript requiring the use of generics?

const typeFunction = <T>(a:string, {c,d} = {c: T[], D:T} = {})=>{} In what way does TypeScript enforce the usage of generics? I am looking to create a function that requires a specific type (T) to be passed in when it is used. typeFunction<st ...

Analyzing reporting tools for a project using Angular 7

We're embarking on a new web project using Angular7 and need to select the right web-based reporting tools for creating system reports within the application, possibly allowing users to design their report templates on-the-fly. Despite extensive onlin ...

Harnessing the power of Material-UI's muiThemeable with Typescript

I'm trying to access the current theme colors within a custom React component. The example I'm referencing is from Material UI http://www.material-ui.com/#/customization/themes Despite attempting various approaches, I'm unable to get Typesc ...

The component has reached the maximum limit of recursive updates

I have been working on a simple fetching function and encountered a warning message: The warning states: Maximum recursive updates exceeded in component. This indicates that a reactive effect is mutating its dependencies, causing it to trigger itself recu ...

Firebase Promise not running as expected

Here is a method that I am having trouble with: async signinUser(email: string, password: string) { return firebase.auth().signInWithEmailAndPassword(email, password) .then( response => { console.log(response); ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

Having trouble with Angular 2 Kendo's toOdataString function returning an empty string?

When sending the object below: { "logic":"and", "filters":[ { "logic":"or", "filters":[ { "field":"text", "operator":"neq", "value":"" } ...

Is it possible to overlook specific attributes when constructing an object using TypeScript interfaces?

I have defined an interface with various properties. I am looking to instantiate an object based on this interface, but I only want to partially initialize some of the properties. Is there a way to accomplish this? Thank you. export interface Campaign { ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

warning TS2322: Cannot assign type 'PropUser | null' to type 'PropUser'

Issue: Error: src/app/user/containers/shell-user-profile/shell-user-profile.component.html:1:20 - error TS2322: Type 'PropUser | null' is not assignable to type 'PropUser'. Type 'null' is not assignable to type 'Pro ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

What is the best way to test the SSM getParameter function using Jasmine?

Is there a way to effectively test this? const ssmParameterData = await ssm.getParameter(params, async (error, data) => { if (error) throw error; return data; }).promise(); I have attempted mocking the method by doing: spyOn(ssm, 'getParameter& ...

React experimental is encountering an issue with missing property "" $fragmentRefs"" when relaying fragments

Details Recently, I decided to explore React experimental features with concurrent mode and relay. Even though I have never used relay before, I managed to make progress but ran into some issues. Initially, using the useLazyLoadQuery hook without any frag ...

What is the reason behind the command "npm-install" placing files directly into the root directory?

After pulling my front-end project from the repository, I noticed that the node_modules folder was missing. My usual approach is to use npm install to get all the dependencies listed in the package.json file installed. However, this time around, I ended u ...