Angular Rxjs在类中

时间:2019-05-08 13:21:06

标签: angular rxjs this subscribe

在我的Angular 7应用程序中,我实现了一些代码来获取创建“后退按钮”样式功能的最后一页路由。它似乎可以工作并在事件触发时设置this.referringRoute,但是如果我尝试在类中的其他任何地方引用this.referringRoute,则它是未定义的。我在可观察对象中使用箭头函数,因此我会假设订阅中提到的“ this”的作用域仅限于this类,对我要去哪里出错有任何想法吗?谢谢:)

export class DetailsComponent implements OnInit {

    referringRoute: string;

    ngOnInit(): void {
        //get last page route and set to class variable
        this.router.events
            .pipe(filter((e: any) => e instanceof RoutesRecognized),
                pairwise()
            )
            .subscribe((e: any) => {
                this.referringRoute = e[0].urlAfterRedirects;
                console.log("PREVIOUS URL:", this.referringRoute); // previous url, logs as expected
            });
    }


    goBack() {
        console.debug("close called:", this.referringRoute); // this.referringRoute is always undefined
        if (this.referringRoute) {
            this.router.navigate([this.referringRoute]);
        } else {
            this.router.navigate(['/plants/collections']);
        }
    }
}
像这样从模板调用

goBack

<div (click)="goBack()">

0 个答案:

没有答案
相关问题