如何初始化订阅对象

eta*_*nae 1 rxjs typescript angular

我正在使用订阅从角度路径中获取参数。这是代码:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription} from 'rxjs';


@Component({
    selector: 'farm-house',
    templateUrl: './house.component.html',
    styleUrls: ['./house.component.scss']
})
export class GreenhouseComponent implements OnInit, OnDestroy {
    
    private routeSub: Subscription;
    id: string;

    constructor(private route: ActivatedRoute) {
        this.id = "";
    }

    ngOnInit(): void {
        this.routeSub = this.route.params.subscribe(params => {
            this.id = params['id'];
        });
    }

    ngOnDestroy() {
        this.routeSub.unsubscribe();
    }
}

Run Code Online (Sandbox Code Playgroud)

但问题是编译器说:

属性“routeSub”没有初始值设定项,并且未在构造函数中明确分配。

我的问题是,初始化订阅对象的最佳方法是什么?

eta*_*nae 7

我提出了另一个使用此问题Subscription.EMPTY的解决方案。

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription} from 'rxjs';


@Component({
    selector: 'farm-house',
    templateUrl: './house.component.html',
    styleUrls: ['./house.component.scss']
})
export class GreenhouseComponent implements OnInit, OnDestroy {
    
    private routeSub: Subscription;
    id: string;

    constructor(private route: ActivatedRoute) {
        this.routeSub = Subscription.EMPTY;
        this.id = "";
    }

    ngOnInit(): void {
        this.routeSub = this.route.params.subscribe(params => {
            this.id = params['id'];
        });
    }

    ngOnDestroy(): void {
        if(this.routeSub) {
            this.routeSub.unsubscribe();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)