2016-05-24 31 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(); 

修复了所有我的问题。

相关问题