我应该从构造函数()或ngOnInit()实例化一个Observable吗?

时间:2018-04-12 11:03:39

标签: angular rxjs observable ngrx ngrx-store

我一般都知道,应该在构造函数中实例化实例变量和依赖项,无论是注入,new'编辑,还是来自@ngrx/store select()

@Component
export class MyCoolComponent implements OnInit {
    public coolObservable$: Observable<any>;
    public myItems$: Observable<Item[]>;

    constructor(private myCoolService: CoolService, private store: Store) {
        // Instantiate the Observables here?
        this.coolObservable$ = Observable.of('cool!');
        this.myItems$ = this.store.select('items');
    }

    public ngOnInit() {
        // Or instantiate the Observables here?
        this.coolObservable$ = Observable.of('cool!');
        this.myItems$ = this.store.select('items'); 
    }
}

Angular中的最佳做法是什么?

1 个答案:

答案 0 :(得分:3)

ngOnInit()用于确保您使用的组件属性已初始化。例如,在以下代码中调用返回getProductById()的构造函数Observable中的代码将是错误的,因为属性productId将是未定义的:

@Input() productId: number;

constructor(private productService: ProductService) {}
        
ngOnInit() {
          
  this.product = this.productService.getProductById(this.productId);
}

但是在你的情况下,你只是在构造函数中初始化两个变量而不使用任何组件属性,所以在构造函数中保留这些代码就可以了。

话虽如此,一些纯粹主义者会对构造函数中的任何代码感到沮丧,但纯粹主义者并不总是正确的:)。