我应该从constructor()或ngOnInit()实例化一个Observable吗?

Dol*_*lan 5 observable rxjs ngrx angular 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'); 
    }
}
Run Code Online (Sandbox Code Playgroud)

什么是最佳做法Angular

Yak*_*ain 6

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

@Input() productId: number;

constructor(private productService: ProductService) {}?        
ngOnInit() {?          
  this.product = this.productService.getProductById(this.productId);
}
Run Code Online (Sandbox Code Playgroud)

但是在您的情况下,您只需在构造函数中初始化两个变量而不使用任何组件属性,因此将此代码保留在构造函数中是可以的。

话虽如此,一些纯粹主义者会不赞成在构造函数中包含任何代码,但纯粹主义者并不总是正确的:)。