2017-01-17 111 views
2

在我的商店中,我有isLoading:布爾值,當服務器的請求開始並且在respose之後或錯誤時它變回false時,它是false並更改爲true。我在容器類選擇它,並傳遞到組件的屬性是這樣的:Angular 2 ngrx Observable value

@Component({ 
    template: `<some-component [isLoading]="isLoading"></some-component>` 
}) 

class SomeContainer() { 
    private isLoading: Observable<boolean>; 
    constructor(private store: Store<IStore>) { 
    this.isLoading = store.select(isLoadingSelector); 
    } 
} 

而且我想使用它的一些條件內容:

class SomeComponent { 
    @Input() private isLoading: Observable<boolean>; 
    ... 
} 

<div> 
    <span *ngIf="isLoading">Loading</span> 
    <span *ngIf="!isLoading">Some data</span> 
</div> 

但isLoading是可觀察的,我必須得這個邏輯的預期工作的布爾值。我找到了解決辦法是越來越值類是這樣的:

private ngOnInit():void { 
    this.isLoading.subscribe((value) => this.isLoadingBoolean = value); 
} 

,並在模板中使用isLoadingBoolean。

但它看起來很棘手。有沒有更好的方法來解決這個問題(也許是用* ngIf使用async管道的方法)?

+0

你試過'* ngIf =「!(isLoading | async)」'? – chrigu

回答

3

可以使用async管你SomeContainer

@Component({ 
    template: `<some-component [isLoading]="isLoading | async"></some-component>` 
}) 
class SomeContainer() { 
    private isLoading: Observable<boolean>; 
    constructor(private store: Store<IStore>) { 
    this.isLoading = store.select(isLoadingSelector); 
    } 
} 

而且你SomeComponent可以簡化使用boolean輸入:

@Component({ 
    template: ` 
    <div> 
     <span *ngIf="isLoading">Loading</span> 
     <span *ngIf="!isLoading">Some data</span> 
    </div> 
    ` 
}) 
class SomeComponent { 
    @Input() private isLoading: boolean; 
    ... 
} 

通常情況下,這是對付一個好主意與容器中的可觀察物體一起使得組件可以是'啞'的 - 參見"Presentational and Container Components"