2016-05-24 62 views
1

EventSpinner組件訂閱EventsService提供的圖標。提供Subject Subject的服務不會收到通知

@Component({ 
    selector: 'event-spinner', 
    template: ` 
<div class="col-xs-5"> 
    Test <i class="fa fa-2x" [ngClass]="{'fa-check': icon == 'ok', 'fa-spin': icon == 'loading', 'fa-spinner': icon == 'loading', 'fa-times': icon == 'error'}" id="spin"></i> 
</div> 
    ` 
}) 
export class EventSpinner implements OnInit { 
    icon: string; 

    constructor(public eventsService: EventsService) { 
    } 

    ngOnInit(): void { 
     this.eventsService.icons.subscribe((icon) => { 
      let old = this.icon; 
      this.icon = icon; 
      console.log("this.icon = " + this.icon + " (was " + old + ")"); 
     }); 
    } 

} 

icons.next在使用@角/ http.get狀態變化( 「加載」/ 「OK」/ 「錯誤」)的web服務請求調用。然而,當這種情況發生時,i標籤的類不會被更新。任何想法?

EventsService.ts

@Injectable() 
export class EventsService { 
    icons: Subject<string> = new Subject<string>(); 

    constructor(public http: Http) { 
    } 

    subscribe(): Observable<Event[]> { 
     let url = (<any>window).__ext.API_URL + 'event/view'; 
     let obs; 
     return Observable 
      .create((o) => { 
       obs = o; 
       obs.next(); 
      }) 
      .flatMap(() => { 
       this.icons.next("loading"); 
       console.log("executing request"); 
       return this.http.get(url) 
      }) 
      .retryWhen(error => { 
       this.icons.next("error"); 
       return error.delay(3000); 
      }) 
      .map((response: Response) => { 
       this.icons.next("ok"); 
       console.log("response received"); 
       setTimeout(() => { 
        console.log("pushing next"); 
        obs.next(); 
       }, 1000); 
       return (<any>response.json()).map(item => { 
        return item; 
       }); 
      }); 
    } 
} 
+0

是否在觸發事件時顯示console.log? –

+0

什麼是'EventsService'? –

+0

@ThierryTemplier是 – zpul

回答

1

它可能由EventService實施後可能造成或可能與ngClass一個問題,但手動調用變化檢測應該解決的問題:

export class EventSpinner implements OnInit { 
    icon: string; 

    constructor(public eventsService: EventsService, private cdRef:ChangeDetectorRef) { 
    } 

    ngOnInit(): void { 
     this.eventsService.icons.subscribe((icon) => { 
      let old = this.icon; 
      this.icon = icon; 
      console.log("this.icon = " + this.icon + " (was " + old + ")"); 
      this.cdRef.detectChanges(); 
     }); 
    } 
} 
+0

This Works ...你能猜到爲什麼變化不會被自動檢測到嗎?這是一個錯誤還是什麼?提前致謝。 – zpul

+0

這可能是Angular或zone中的一個錯誤。這可能與您的項目設置有關。例如,錯誤版本的RxJS或某些polyfills應用了錯誤的方式。我在這裏沒有太多的知識,因爲我只使用Dart。 –

0

使用:

new Observable(...); 

new BehaviorSubject(...); 

,而不是靜態

X.create(); 

修復了所有我的問題。

相關問題