@Component({
selector: 'app-user',
styleUrls: ['./user.component.css'],
template: `
<button (click)="clickSearch('some keyword')">Search</button>
<div *ngIf="books$ | async as books">
<h5 *ngIf="hasSearched">No. of books: {{ books.length }}</h5>
<p *ngIf="hasSearched && !books.length">No books found</p>
<p *ngIf="!hasSearched">Please enter a search keyword to start searching for books.</p>
<h2 *ngFor="let book of books">{{ book.title }}</h2>
</div>
`
})
export class UserComponent {
constructor(private store: Store) {}
hasSearched: boolean = false;
books$ = this.store.select(BooksSelector.getBooks)
.pipe(
tap(data => console.log(data))
);
clickSearch(keyword: string) {
this.hasSearched = true;
this.store.dispatch(BooksActions.loadBooksFromApi(
{ q: keyword …Run Code Online (Sandbox Code Playgroud) ngOnInit当 Observable 在类属性声明级别初始化时,为什么当异步管道解开 Observable 时管道没有被触发?
我知道我可以自己进行初始化,ngOnInit但我只是想更好地了解 RxJS 流的工作原理。我也知道我可以打电话subscribe()过来ngOnInit,但这不是我的本意。
我尝试过添加假加载来“延迟”模板渲染,希望延迟异步管道,但它仍然不起作用。
成分:
export class MyComponent implements OnInit {
constructor(
private dataService: DataService
) { }
items$: Observable<Item[]> = this.dataService.getItems();
ngOnInit(): void {
this.items$.pipe(
tap(data => {
console.log('items', data); // <--- this doesn't get called
})
)
}
}
Run Code Online (Sandbox Code Playgroud)
模板:
<div *ngFor="let item of items$ | async">{{ item.name }}</div>
Run Code Online (Sandbox Code Playgroud)