Exploring the power of the RxJS subscribe operator within Angular 2's observable framework

Below is the TypeScript file for my service.

import {Injectable} from '@angular/core';
import {Http, HTTP_PROVIDERS, Request, RequestOptions, Response, Headers} from '@angular/http';
import {Observable} from 'rxjs/Observable';

@Injectable()
export class CarService {
    constructor(private http: Http) { }
    Url: string = 'url/of/api';
    getCar(){
        var headers = new Headers();
            headers.append('API-Key-For-Authentification', 'my_own_key_goes_here');
            headers.append('Accept', 'application/json');
        var options = new RequestOptions({ headers: headers })
        return this.http.get(this.Url, options)
            .map((res: Response) => res.json())
    }
}

The above code snippet is injected into the component below.

import {Component} from '@angular/core';
import {CarService} from 'path/to/car.service';

@Component({
    selector: 'home',
    providers: [ CarService ],
    template: `
        <div>
            <button (click)="getCar()">Get Car</button>
            <h2>The car has {{ tiresCount }} tires.</h2>
        </div>
    `
})
export class Home {
    tiresCount: number;
    constructor(private carService: CarService) { }
    getCar() {
        this.carService.getCar()
            .subscribe(function(data){
                this.tiresCount = data.tires.count;
                console.log(this.tiresCount); // 4
        };
        console.log(this.tiresCount); // undefined
    }
}

I am trying to display the number of tires in the view of the Home component when the button is clicked. However, I noticed that when I console.log(this.tiresCount) inside the .subscribe, it logs 4 but outside of it, it logs undefined. This suggests that the local property tiresCount did not receive the updated value and therefore does not display anything in the view.

I feel like I might be overlooking something obvious or perhaps I need a better understanding of Observables and RxJS since I am still relatively new to them.

Answer №1

Opt for using a lambda expression or commonly known as an arrow function instead of the traditional function(){..} syntax when implementing your subscribe method. By doing so, you ensure that this points to the correct context, specifically the Home component class.

fetchData() {
    this.dataService.getData()
            .subscribe(response => {
                this.result = response.value;
                console.log(this.result); // 42
    });
    console.log(this.result); // undefined
}
anotherFunction(){
    console.log(this.result); // 42 , only after getData().subscribe() is completed 
}

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

Unable to load `fs-extra` using `require()`: encountering error message "Module fs-extra not found"

Having trouble utilizing installed npm packages like fs-extra in the js files provided by Truffle. The error message "can't find module 'fs-extra'" keeps popping up. 1) Attempted to import local js files using the require() method, but it w ...

Encountering an issue when trying to generate a button in Angular

I am currently using JavaScript to dynamically create a button in Angular. While I have been successful in creating the button, I am encountering an error when attempting to change the classname. The error message I am receiving is: Property 'clas ...

Comparable to LINQ SingleOrDefault()

I frequently utilize this particular pattern in my Typescript coding: class Vegetable { constructor(public id: number, public name: string) { } } var vegetableArray = new Array<Vegetable>(); vegetableArray.push(new Vegetable(1, "Carrot")); ...

Tips for adding href in Angular2

Check out this template example: <a href="#" (click)="goToPost()">{{post.title}}</a> Here's the goToPost() function: goToPost() { this.router.navigate(['/post', this.post.id]); } The resulting link will be: mysite.dev/pos ...

What is the syntax for declaring a list of JSON objects in TypeScript?

I've been attempting to implement something similar to the following: interface IUser { addresses: JSON = []; } Unfortunately, it doesn't seem to be working! I'm looking to store a list of nested JSON objects inside the addresses field, ...

When looking for a selection, the drop-down list unexpectedly shifts upwards

When using the ngx-intl-tel-input library in my Angular application, I noticed that when searching for a country in the dropdown list, it moves to the top. I am looking to fix the position of the dropdown menu while searching. Check out the demo: Demo Lin ...

Working with button loops in react.js

Just started learning react.js and I'm trying to display a list of names as buttons. const exampleComponent: React.FC<IProps> = () => { const renderButtons= () => { for(let i=0; i<names.length; i++){ <TextButt ...

Retrieve data from an HTML form within an Angular 2 ag-grid component

I'm facing a challenge with incorporating form values from a modal into an ag-grid array in my HTML file. I'm unsure of the process to achieve this. Below is an excerpt from my file.html: <template #addTrainContent let-c="close" let-d="dismi ...

Angular2 is being impacted by two components that are causing interference with file events

I am facing an issue with having two instances of a component named FileUploadComponent. The purpose of this component is to listen for file events and emit them to its hosting component using an EventEmitter. Despite its seemingly simple functionality, w ...

ResizableBox is failing to render any content

My current project involves trying out react-resizable. Unfortunately, my basic example only shows the text XYZ in the browser without displaying any resizable box as expected. There are no error messages either. import { ResizableBox } from 'react-re ...

How can I accurately determine the parameters of an ellipse that represents the trajectory of an object in space using initial condition values (r0, v0, deltat, and mu)?

In my current game project, I'm developing a primary user interface that displays the solar system from a top-down perspective (with Earth's north pole as 'up'). One of the challenges I faced was creating a semi-realistic path for an ob ...

Inconsistency with Context Values in NextJS: Production Environment Shows Undefined Values (while Development Environment Works as

A feature called "dark mode" has been successfully integrated into my Next.js application using the React Context API. While everything functions properly during development, issues related to the Context provider have surfaced in the production version ...

Stay Alert: Angular Observable Continuously Monitored for Promise Updates

I am currently working on an angular application that has a connection with a printer. The printer possesses its own status service that is implemented as a promise, providing the printer's current status as a response. However, I am facing an issue w ...

ng-bootstrap: NgbModalRef provider not found - NullInjectorError

I am facing an issue when trying to incorporate the NgbModalRef class into my component. Despite having Angular 10.2.1, Bootstrap 4.5.3, and ng-bootstrap 8.0.4 installed, I am unable to inject the class successfully. In my app.module file, I have added the ...

Using Observable<any> as an input argument in a child component

When a button is clicked, a different Observable is loaded. In the main component, I have this : <button (click)="onClickMe1()">Click me 1!</button> <button (click)="onClickMe2()">Click me 2!</button> However, nothing appears in ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

Is there a way to have the first entry automatically selected and displayed when the page loads?

My ngModel and ngchange are set up to bind to a JSON array in the ts file and display its contents. When the page loads, I want the first entry to be already selected and its content shown. Currently, the screen is blank upon loading, and the content only ...

Can the Okta Sign-In Widget be tailored to incorporate Angular Material elements?

I’ve recently integrated the @okta/okta-signin-widget into my Angular SPA, and it displays as follows: <span> <input id="okta-signin-username" type="text"> </span> My Angular SPA is styled using the Angular Mate ...

I'm having trouble with implementing a basic show/hide feature for the login and logout options in the navigation bar using Angular. Can anyone help me figure out why it's

Is there a way to display the functionality after logging in without using session storage or implementing the logout function? The HTML for navigation is provided below. <nav class="navbar navbar-expand-sm navbar-light bg-light"> ...

Best Practices for Customizing Angular 5 node_module .js Files

After searching through Google and Stackoverflow, I realize that my query may be common. It seems like I might not be using the correct search terms. In my current Angular 5 Project, I have integrated pdfmake by executing the command npm i --save pdfmake. ...