如何初始化订阅对象

How to initialize a Subscription object

我正在使用订阅从 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();
    }
}

但问题是编译器说:

Property 'routeSub' has no initializer and is not definitely assigned in the constructor.

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

大多数情况下,在取消订阅之前检查订阅就足够了。

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

在您的情况下,不需要初始化订阅,因为您已经在 ngOnInit() 中调用了 subscribe 方法。可能会出现错误,因为您直接在 Subscription 上调用 unsubscribe(),而没有检查它是否已初始化。

如果你声明 routeSub: any; 编译器不应该抱怨。 资料来源:在 看到它完成,我为我工作

我想出了另一个解决方案,它使用 中的 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();
        }
    }
}

应该就是

private routeSub: Subscription = new Subscription

这对我有用。