2016-08-25 39 views
0

我實際上遇到了區域問題。我在一個名爲App的ngmodule中有一個組件,調用另一個名爲「tache-list」的組件,從另一個名爲「Dossier」的ngmodule(App imports Dossier)中調用。 我用TacheService發送一個http請求,返回我的taches(任務),並且我想用我的TacheListComponent打印它們。但是,加載頁面時,沒有更改檢測。我做了很多研究,並發現了一些關於區域和角度區域的文檔。我試圖使用NgZone.run(),並且這次檢測到了變化。 這怎麼可能?有沒有比在我的所有服務功能中粘貼運行功能更好的方法?謝謝你的迴應,似乎對角區的信息是罕見的...組件/服務,更改檢測和區域

環節,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; 
    } 
} 
+0

如果你不希望它在你的服務函數中,你可以在訂閱的下一個處理程序中完成。你是在網頁,桌面還是手機上做這個? – scottmgerstl

+0

在網上。訂閱的下一個處理程序是什麼意思?在我的組件? – Pythorogus

+0

是的,在你的組件中。 taches => this.zone.run(()=> this.taches = taches); Obserables有三個可以提供給訂閱的函數:onNext,onError,onComplete。這裏是一個資源審查:https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/subscribe.md – scottmgerstl

回答

1

發現問題,我加載的zone.js文件的順序不合適。非常愚蠢......感謝您的回答。