Reputation: 395
i'm actually in trouble with zone. I have a component, in a ngmodule called App, calling another component called "tache-list", from another ngmodule called "Dossier" (App imports Dossier). I send a http request, with a TacheService, returning my taches (tasks), and i want to print them with my TacheListComponent. However, when page is loaded, there is no change detection. I made many researchs, and found some documentation about zone and Angular Zone. I tried to use NgZone.run(), and this time the taches changes are detected. How is that possible ? is there a better way than paste the run function in all my service functions ? Thank you for you respond, it seems that informations about angular zone are rare...
tache-list.component.ts :
import { Component, OnInit } from '@angular/core';
import { TacheService } from '../services/tache.service';
import { Tache } from '../entities/tache.ts';
import { ChangeDetectorRef } from "@angular/core";
import 'rxjs/Observable';
import 'rxjs/add/operator/toPromise'
@Component({
selector: 'tache-list',
templateUrl: 'build/dossier/partials/tache-list.component.html',
styleUrls: ['build/dossier/css/tache-list.component.css']
})
export class TacheListComponent implements OnInit {
title: String = 'Liste des tâches';
taches: Object[];
errorMessage: any;
subscriptions: any[] = [];
constructor(private tacheService: TacheService, private changeDetector: ChangeDetectorRef) { }
ngOnInit() {
this.getTachesDuJour();
}
ngOnDestroy() {
this.subscriptions.forEach(sub => {
sub.unsubscribe();
});
}
getTachesDuJour() {
return this.tacheService.getTachesDuJour().subscribe(
taches => {
this.taches = taches;
//this.changeDetector.detectChanges();
},
error => {
this.errorMessage = <any>error;
}
);
}
}
tache.service.ts :
import { Injectable, OnInit, NgZone } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class TacheService implements OnInit {
url: string = 'http://web-pierre/ebexapplication/public/api/tache';
constructor(private http: Http, private zone: NgZone) { }
ngOnInit() {
}
private extractData(res: Response) {
let body = res.json();
return body || {};
}
private handleError(error: any) {
let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg);
return Observable.throw(errMsg);
}
getTachesDuJour(): Observable<Object[]> {
this.zone.run(() => {});
var response = this.http.get(this.url).map(res => this.extractData(res)).catch(this.handleError);
return response;
}
}
Upvotes: 0
Views: 399
Reputation: 395
Found the problem, I was loading in bad order the zone.js file. So dumb... Thanks for your answers.
Upvotes: 1