简体   繁体   中英

Storing observable data into global variable returns 'undefined' in Angular 4

I am currently working with a node server that I've set up and created an endpoint /user-info which res.send({id: <my-id>, name: <my-display-name>})

On Angular I have created a global.service.ts file that will call this endpoint using http.get and subscribe that data and store into two variables I have declared.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class Globals {

    constructor(private http: HttpClient) { }

    public id: string;
    public name: string;

    userInfo() {
        this.http.get('/user-info').subscribe(
            (data: any) => {
                this.id = data.id;                    
            }
        );
        console.log(this.id);
    }

}

Once I console.log(this.id) it returns undefined . I have already the server-side to see if that was causing the problem but it returns a string.

In my server.js file (node server) I am working with express. This is the endpoint:

app.get('/user-info', function(req, res) {
    client.get('id', (err, data) => {
        client.get('name', (err, reply) => {
            res.send({id: data, name: reply})
        })
    })
})

I am using redis to store values 'id' and 'name' and the client.get is just a redis command used to call those values from cache. I have tested just checking localhost:8000/user-info and everything looks fine.

Am I missing/misunderstanding something? Thanks!

if console.log still outside of call, it will execute before you got a response. Try this:

userInfo() {
        this.http.get('/user-info').subscribe(
            (data: any) => {
                this.id = data.id
                console.log(this.id);
            }
        )

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM