0

How to access the JSON attributes in typescript ?

As I am making Angular Project.
`

    test:string;
    response:any;

    web_assign() {
    this.http.get(this.url1).subscribe( e => this.response = e);
    this.test = "OK";
    this.t=this.response.name2;
    return false;}

it is giving error on this line. this.t=this.response.name2; It says that it cannot read property of 'name2'

1 Answer 1

1

You need to do the assignment inside the subscribe callback:

this.http.get(this.url1)
    .subscribe( e => {
        this.response = e;
        this.test = "OK";
        this.t=this.response.name2;
    });

http.get is async and this.response will still not be defined on the next line, but it will be defined in subscribe callback.

Sign up to request clarification or add additional context in comments.

1 Comment

based on his repoutation score, he can not accept, but here is my upvote for you XD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.