Issue with Angular 2: Service not reflecting updated variable

I am currently working on creating an API service and trying to assign the data to a variable. However, I am facing an issue where the variable is not updating and ends up being undefined when I try to log it after calling the API service.

import {Component,Input,Output,EventEmitter} from 'angular2/core';
import {NgClass,NgFor} from 'angular2/common';
import {Observable} from 'rxjs/Observable';
import {ChangeDetectionStrategy} from 'angular2/core';
import {ValuesPipe} from '../pipes/values';
import {ApiRequestService, Query} from '../services/apiRequestService';

@Component({
selector: 'browsePCLatestRelease',  
directives: [NgClass,NgFor],
changeDetection: ChangeDetectionStrategy.OnPush,
pipes: [ ValuesPipe ],
styles: [ require('./browsePCLatestRelease.less') ],
template: require('./browsePCLatestRelease.html')
})
export class browsePCLatestRelease {

public arrayOfKeys;
pcLatestrelease:Array<any> ;
query: Query;

constructor(private _apiService: ApiRequestService) {
}

ngOnInit() {

this.query = this._apiService.createQuery('browsePC.getIssue');
this.query.params({
  volume: '60',
  issue: '50'
});
this._apiService.execute(this.query)
  .subscribe(

    data => this.pcLatestrelease=data,
    error => console.log(error),
    () => console.log('pcLatestrelease retrieved')

  );

console.log('this.pcLatestrelease');
console.log(this.pcLatestrelease);  

}


}

HTML

<div *ngFor = "#thisRelease of pcLatestrelease">
        {{thisRelease.title}}
</div>

If anyone has any insights or solutions, I would appreciate your help. Thank you in advance.

Answer №1

The function does not execute line by line in the order listed

export class browsePCLatestRelease {

  ...

  ngOnInit() {

    this.query = this._apiService.createQuery('browsePC.getIssue');
    this.query.params({
      volume: '60',
      issue: '50'
    });
    this._apiService.execute(this.query)
    .subscribe(
  // A function is passed to subscribe of an observable
  // This function gets called when data arrives from the server
      data => this.pcLatestrelease=data,
      error => console.log(error),
      () => console.log('pcLatestrelease retrived')
    );

  // The following code is executed immediately after the function is passed to subscribe, 
  // but the function has not been executed yet
    console.log('this.pcLatestrelease');
    console.log(this.pcLatestrelease);  // logged as undefined
  }
}

When the data eventually arrives

data => this.pcLatestrelease=data,

the above code is executed and the value is assigned to this.pcLatestrelease

If you want your code to be executed after the data arrives, use

export class browsePCLatestRelease {

  ...

  ngOnInit() {

    this.query = this._apiService.createQuery('browsePC.getIssue');
    this.query.params({
      volume: '60',
      issue: '50'
    });
    this._apiService.execute(this.query)
    .subscribe(
  // A function is passed to subscribe of an observable
  // This function gets called when the data arrives from the server
      data => {
         this.pcLatestrelease=data;
         console.log('this.pcLatestrelease');
         console.log(this.pcLatestrelease);  // logged as undefined
      },
      error => console.log(error),
      () => console.log('pcLatestrelease retrived')
    );

  }
}

update

import {Component,Input,Output,EventEmitter, NgZone} from 'angular2/core';

...

export class browsePCLatestRelease {

  constructor(private _apiService: ApiRequestService, private _zone.NgZone) {
  }    

  ...

  ngOnInit() {

    this.query = this._apiService.createQuery('browsePC.getIssue');
    this.query.params({
      volume: '60',
      issue: '50'
    });
    this._apiService.execute(this.query)
    .subscribe(
  // A function is passed to subscribe of an observable
  // This function gets called when the data arrives from the server
      data => {
         this.zone.run(() => {
           this.pcLatestrelease=data;
           console.log('this.pcLatestrelease');
           console.log(this.pcLatestrelease);  // logged as undefined
         });
      },
      error => console.log(error),
      () => console.log('pcLatestrelease retrived')
    );

  }
}

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

Tips for confirming a sub string is present in an array using JavaScript/TScript

I am currently testing for the presence of a SubString within an array. In my test, I am asserting using: expect(classList).toContain('Rail__focused') However, I encountered the following error: Error: expect(received).toContain(expected // inde ...

Is there a way to utilize an Event Emitter to invoke a function that produces a result, and pause until the answer is provided before continuing?

Looking for a way to emit an event from a child component that triggers a function in the parent component, but with a need to wait for a response before continuing. Child @Output() callParentFunction = new EventEmitter<any>(); ... this.callParen ...

Executing file upload in parent component with Angular 2

Is there a way to initiate a file upload from the parent component of the router? Specifically, I need to execute two functions located in the parent component - openFileSelect and uploadSelectedFile to manage the <input type="file"> element. This i ...

Understanding how to retrieve the Request Header value when entering my Angular application

My Angular application needs to be accessed from another external or internal application. The request sent from this application includes specific information in the Request Header that I need to identify where it is coming from. However, I am strugglin ...

I'm currently endeavoring to integrate SignalR into my Vue project and encountering an issue

Currently, I am working on a project using Vue with TypeScript and I am interested in integrating SignalR. I have thoroughly studied the documentation provided by '@dreamonkey/vue-signalr' on how to utilize SignalR. import { VueSignalR } from &ap ...

Tips for verifying the Reactive formControl/formArray when submitting

In my scenario, I am working with a FormGroup titled Parent, which includes a FormArray as a control. This FormArray consists of another FormGroup referred to as the Child. Main Goal The main objective here is to perform validation on all controls of a sp ...

Function exported as default in Typescript

My current version of TypeScript is 1.6.2 and we compile it to ECMA 5. I am a beginner in TypeScript, so please bear with me. These are the imported library typings. The contents of redux-thunk.d.ts: declare module "redux-thunk" { import { Middle ...

Oops! There seems to be an issue with the code: "TypeError: this

I am just starting out with Angular. Currently, I need to assign a method to my paginator.getRangeLabel (I want to use either a standard label or a suffixed one depending on certain conditions): this.paginator._intl.getRangeLabel = this.getLabel; The cod ...

Observable<Any> Filter

I am currently utilizing Typescript and Angular 4 in my work. Within my project, I have two lists implemented using rxjs/Rx. ... myList: Observable<MyClass[]>; filteredList: Observable<MyClass[]>; ... My objective is to filter the myList base ...

An issue arose while compiling the template for 'AppRoutingModule', indicating that function expressions are not compatible with decorators

Currently, I have implemented the "CaseInsensitiveMatcher" based on the solution suggested by Alireza. However, I am facing an issue when attempting to create a production build as indicated by the following error message: "'urlMatch' referenc ...

What is the best way to incorporate "thread.sleep" in an Angular 7 app within a non-async method like ngOnInit()?

Despite the numerous questions and solutions available on Stack Overflow, none of them seem to work when called from a component's init function that is not asynchronous. Here's an example: private delay(ms: number) { return new Promise( ...

Having difficulty importing SVG files in TypeScript

When working with TypeScript (*.tsx) files, I encountered an issue where I couldn't import an SVG file using the following statement: import logo from './logo.svg'; The transpiler gave me this error message: [ts] cannot find module '. ...

What is the best way to prevent re-initialization of a child component when there are changes in the

I'm currently developing an application that features a wall similar to Facebook, complete with post components (each post displaying a like counter) and nested comment components which are loaded on demand with a button within the post. My implementa ...

Angular 4's OrderBy Directive for Sorting Results

I've been working on implementing a sorting pipe based on the code provided in this resource: The issue I'm facing revolves around handling undefined values within my data. The sorting pipe functions correctly when there are no undefined values ...

Guide to keep the loader running until the API response is retrieved in Ionic 4

I'm currently developing an app using Ionic 4 where I am retrieving data from an API. To enhance user experience, I have included a loader on the front page that shows while the data is being fetched. My goal is to keep the loader running until the d ...

Learn the steps to establish a one-to-many relational record with the help of Node.js and Sequelize-Typescript

Currently, I am working on Nodejs with sequelize-typescript to develop a CRUD system for a one-to-many relationship. Unfortunately, I have encountered an issue with my code that I cannot seem to pinpoint. While I am able to retrieve records successfully us ...

Utilizing TypeScript in conjunction with Vue and the property decorator to assign default values to props

Hey there! I'm currently dealing with a property that looks like this, but encountering a type error when trying to translate text using i18n @Prop({ default: function() { return [ { > text: this.$t('wawi_id'), align: ...

Tips for verifying that parameters possess designated characteristics in TypeScript

How can I ensure that data2 and data3 work correctly, while data1 triggers an error if the data type is not specified as shown in the code below? I need to validate that when a user enters params like {name: 'aa', age: 20}, it should throw an er ...

Utilizing type guards in prop functions for conditional rendering within React TypeScript adds an extra layer

In my code, I am conditionally rendering a Button. However, I encountered an issue on line 7 where TypeScript is indicating that the first parameter of the exportExcel function may be null even though it should not be, considering the conditional render lo ...

replace the tsconfig.json file with the one provided in the package

While working on my React app and installing a third-party package using TypeScript, I encountered an error message that said: Class constructor Name cannot be invoked without 'new' I attempted to declare a variable with 'new', but tha ...