简体   繁体   中英

How to assign JSON (in a subscribe) to a variable in angular

I have this code snippet where I want to assign res (which logs the whole json), to the json variable , but i'm unable to do it, since the logging of the json variable will return me an undefined object

export class AppComponent {

    title = 'app2';
    json ;

    constructor(private jsl : JsonLoadService)
    {
        this.json = this.jsl.getUrl().subscribe(res => {
            console.log(res);
        });
    }
}

You should do this inside the subscription like below

this.jsl.getUrl().subscribe(res => {
   this.json = res;
   console.log(this.json); // component variable now defined.
})

remember that due to the async nature of subscriptions that this.json will only be defined after the subscription has run. This example should help visualise.

public ngOnInit(): void 
{
    this.jsl.getUrl().subscribe(res => {
       this.json = res;
       this.logData(); // will log your result
    });

    this.logData(); // will not log and will error

}

public logData(): void 
{
    console.log(this.json);
}

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