Using Angular 7 to set the value of an object returned by an observable to a variable

I encountered an issue while trying to assign the return value from a service to a component.

  ngOnInit() {
    this.getInspectionData();
  }

  getInspectionData() {
    this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
      .subscribe(data => {
        console.log(`this is data returned: `, data);
      }, error => {
        console.log('failed to get data', error);
      }, () => {
        console.log('getInspectionResult successfully processed');
      });
  }

The return value was successfully captured in the console.log output.

View console.log result here

Within the subscribe() function, everything appears to be functioning correctly. I even assigned the value to a variable inside the subscribe():

  .subscribe(data => {
    this.inspectionResult = data;
    console.log(`value from getInspectionData: `, this.inspectionResult);

The output of this.inspectionResult was correct.

So, it seemed like everything was in order. However, when I tested it, the variable ended up with an unexpected value of '{}'. Here is the code snippet:

  ngOnInit() {
    this.getInspectionData();
    console.log(`value from getInspectionData: `, this.inspectionResult);
  }

  getInspectionData() {
    this.auctionService.getInspectionResult(`df570718-018a-47d8-97a2-f943a9786536`)
      .subscribe(data => {
        this.inspectionResult = data;
      }, error => {
        console.log('failed to get data', error);
      }, () => {
        console.log('getInspectionResult successfully processed');
      });
  }

See the result here

Additionally, I had initialized the variables as follows:

  inspectionResult: InspectionResult = <InspectionResult>{};
  inspectionResultData: InspectionResultData = <InspectionResultData>{};

My questions are:

  1. Why is the data value not being assigned to this.inspectionResult?
  2. Why is the ngOnInit() not producing the expected output? (The console.log() within ngOnInit() should run after getInspectionData();)

Answer №1

It's possible that the issue is related to

calling this.getInspectionData(); console.log(value from getInspectionData:, this.inspectionResult);

In this scenario, there might be a delay in the execution of this.getInspectionData(), causing console.log() to run before the method completes.

Make sure to await the completion of the method for clarity.

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

When using Firefox to run an Angular dev server with the --ssl flag, an error with the code SEC_ERROR_INADEQUATE_KEY

Currently, I have my angular application running using the command ng serve --port 5001 --ssl --no-live-reload Everything was working fine for a few months until recently when Firefox started having issues loading the page. The error message displayed is: ...

Angular is unable to iterate through a collection of ElementRef instances

My list of ElementRef contains all my inputs, but adding listeners to them seems to indicate that textInputs is empty even though it's not. @ViewChildren('text_input') textInputs!: QueryList<ElementRef>; ngAfterViewInit(): void { ...

Every field displaying a description above the input

Is there a way to customize the default wrapper for all fields? I am looking to have the description displayed above the fields instead of below them, which is the default behavior for Bootstrap. Check out this StackBlitz example: https://stackblitz.com/ ...

How can you effectively declare a computed getter in MobX that aggregates an observable list?

Within my project, I have a class hierarchy consisting of projects, task lists, and tasks. Each array is marked as @observable. Now, I am looking to create a "@computed get allTasks" function within the project class that aggregates all tasks from all task ...

Retrieve a particular element from an array within a JSON object using Ionic

I am currently facing a challenge in extracting a specific array element from a JSON response that I have retrieved. While I can successfully fetch the entire feed, I am struggling to narrow it down to just one particular element. Here is what my service ...

It seems that change detection is triggered by a click event regardless of the detachment setting

My understanding of Angular 2 change detection may be off, but I expected that if a component's ChangeDetectionStrategy was set to Checked, CheckOnce or Detached, the component would only check for changes once upon instantiation. However, it seems to ...

What are the steps to resolve the UglifyJs error stating 'Unexpected token operator'?

When running the following command in my Angular app: > ng build --prod --aot --env=staging I encounter this error message: ERROR in vendor.0625f773941bc83e6748.bundle.js from UglifyJs Unexpected token operator «*», expected punc «(» [vendor.0625 ...

Implement functionality to update the user interface with raw data received through Bluetooth serial communication

I've been utilizing the plugin https://github.com/don/BluetoothSerial to handle my Bluetooth connection with a HC-06 module on an Arduino Leonardo. Everything is functioning well, except for an issue I am encountering with the mobile application. Here ...

Show Firebase data on Angular 6 mat-card in a randomized sequence when the page loads or refreshes

Is it possible to display cards in a random order when the value of a form changes or when the page is refreshed, while fetching data from Firebase? Below is my Component Template: <ng-container *ngFor="let geoToDisplay of geosToDisplay | async"> ...

Error: The type '{ children: Element[]; className: string; }' cannot be assigned to the type 'DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>'

My current setup involves using Next.js and TypeScript While working in Visual Studio Code, I encountered an error message stating Type error: Type '{ children: Element[]; className: string; }' is not assignable to type 'DetailedHTMLProps&l ...

An issue was encountered when attempting to log out the user from Firebase

My website is built using the Ionic and Angular Frameworks along with Firestore database. The signout feature works as expected, but unfortunately, an error occurs when a user tries to sign out of their account. The error message: FirebaseError: Missing o ...

Typescript: Securing Data with the Crypto Module

I am currently working on encrypting a password using the built-in crypto module. Previously, I used createCipher which is now deprecated. I am wondering if there is still an effective way to achieve this. Here is the old code snippet: hashPassword(pass: ...

Create a Typescript type extension specifically designed for objects with nested arrays of objects

After stumbling upon this inquiry, I am eager to adjust my code in a similar fashion, utilizing typescript and a more intricate object. Consider the type below: export type ImportationType = { commercialImportation: boolean dateToManufacturer: string ...

What is the best way to filter and sort a nested tree Array in javascript?

Looking to filter and sort a nested tree object for a menu If the status for sorting and filtering is true, how do I proceed? const items = [{ name: "a1", id: 1, sort: 1, status: true, children: [{ name: "a2", id: 2, ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

Refreshing Angular user interface through asynchronous function

I have an asynchronous method that initializes some variables. The library I'm using provides an onProgress callback that gives the current percentage completed. I want to display this percentage in my view, but for some reason, the view only updates ...

how to send both the useState setter and object as props to a child component in React using TypeScript

Having an issue with passing useState setter and object (both together) to the child component. Successfully passed the object by spreading it like this {...object}, but unsure of the syntax to pass the setter along as well. Here's a code example: < ...

Is it no longer possible to instantiate an object using the syntax <interface>{}?

There seems to be an issue with the code snippet below when run in the TypeScript playground: interface Person { name: string; age: number; } const makePerson= function(name : string, age : number) : Person { let obj = <Person>{} ...

Retrieve particular JSON information on a single webpage by selecting an element on a separate page

My goal is to fetch specific information from a JSON file and display it on different HTML pages by clicking a button. I will achieve this using jQuery and plain JS. For the first HTML page, I want to show all products from the JSON in an element with id= ...

Can the base href in Angular be dynamically changed during runtime?

Within my single Angular application, I have set the base-href to /a/b/. This means that in my dist folder, there is an HTML file with <base href="/a/b/">. As a result, the browser recognizes that an image link like assets/images/logo.png can be foun ...