Arnold Galovics
Arnold Galovics

Reputation: 3416

Angular 2 view not updated after HTTP call

I'm experimenting with Angular 2 and I'm trying to do an http request with the built-in HTTP service:

@Injectable()
export class MyService {
    constructor(private http: Http) {
    }

    public get(): Observable<string[]> {
        return this.http.get('http://localhost:8080/endpoint')
               .map((data) => <string[]>data.json()['content']);
    }
}

Usage is the following:

export class MyComponent implements OnInit {
    public content: string[];

    constructor(private myService: MyService) {
    }

    public ngOnInit(): void {
        this.myService.get().subscribe((data) => {
            this.content = data;
        });
    }
}

If I use zone to run the data assignment, then it works as expected, however I feel that it's a bit hacky and I don't really understand why it is not working.

I read that the code might run outside of angular zone but I don't understand why as I'm only using built-in features.

View binding:

<div *ngFor="let str of content">
    {{ str }}
</div>

Could you please help?

Thanks!

Upvotes: 0

Views: 401

Answers (1)

Arnold Galovics
Arnold Galovics

Reputation: 3416

Turned out that the problem was neither webpack nor my code but the 3rd party code I used.

I implemented Google login based on this answer and as you can see it uses a native JS handler - which I think caused the problem. If I put that code into zone.run, then everything works properly. I think the reason is that the handler ran outside of the zone context and that's why the view was not updated.

Upvotes: 0

Related Questions