在Angular NgRX中,我们通常使用map操作符对Store中的数据进行处理和转换。但是有时候,我们会发现map操作返回的不是一个可观察对象,而是一个普通的对象。这可能会导致一些问题,例如无法执行后续的RxJS操作。
为了解决这个问题,我们可以使用RxJS的of操作符将对象包装成一个可观察对象。下面是一个示例代码:
import { Store, select } from '@ngrx/store';
import { of } from 'rxjs';
interface User {
id: number;
name: string;
}
@Component({
selector: 'app-user-detail',
templateUrl: './user-detail.component.html',
})
export class UserDetailComponent {
user$ = this.store.pipe(
select(selectUser),
map(user => {
if (!user) {
return null;
}
return { ...user };
}),
switchMap(user => {
if (!user) {
return of(null);
}
return of(user);
})
);
constructor(private store: Store) {}
}
在上面的代码中,我们使用map操作符将Store中的用户数据进行了处理。然后使用switchMap操作符将处理后的用户数据转换成一个可观察对象。
需要注意的是,当我们返回一个空的对象时,需要使用of(null)将其包装成一个可观察对象。这是因为RxJS中,当一个操作返回null或undefined时,它将会被认为是一个错误而不是一个空值。
通过以上的修改,我们可以将map操作的返回值转换成一个可观察对象,避免出现一些潜在的问题。