在Angular - NgRx中,.select(...)和.pipe(select...)都是用于在store中选择和订阅某个state的方法。它们的区别在于,.select(...)方法返回的是一个observable对象,而.pipe(select...)方法返回的是一个拥有selector函数的高阶observable对象。
以下是示例代码:
import { Component } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { Observable } from 'rxjs/Observable';
import { AppState } from '../../store/app.state';
import { getPosts } from '../../store/posts/posts.selectors';
@Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.scss']
})
export class PostsComponent {
posts$: Observable;
constructor(private store: Store) {
// 通过.pipe(select...)选择和订阅state,并在回调函数中处理数据
this.posts$ = this.store.pipe(select(getPosts));
// 直接使用.select(...)订阅state,处理数据在回调函数中
this.store.select('posts').subscribe(data => {
console.log(data);
});
}
}
在上面的代码中,我们使用.getPosts选择和订阅了一个posts state作为我们的数据源。在.posts$ observable中处理这个数据。另一方面,通过.store.select(...)直接选择和订阅了一个posts state并在回调函数中处理数据。
上一篇:资源管理器增强-让资源管理器秒变超级英雄,加速、搜索、隐身全攻略
下一篇:Angular-ngserve-Ineffectivemark-compactsnearheaplimitAllocationfailed