如何在Angular 7中修复“在subscribe()函数中赋值的属性返回undefined”[重复]

问题描述 投票:0回答:1

我正在尝试在我的Web应用程序中获取当前的URL或路由,我想出了在angular中使用以下代码执行此操作的方法

```
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Injectable({
providedIn: 'root'
})
export class IncService {

public mainPage: any;

constructor(private router: Router) {

 //get current route
 router.events.subscribe(endUrl => {
   if(endUrl instanceof NavigationEnd ){
     this.mainPage = endUrl.url;
         console.log(this.mainPage); //works perfectly
   }
 });

  console.log(this.mainPage); //does not work, outputs undefined

}

}

```

我希望console.log(this.mainPage)输出当前路由,例如/ home,但我得到'undefined'。

NB我希望'this.mainPage'在我班级的任何地方都可以作为当前的URL而不仅仅是在subscribe()中

javascript angular typescript
1个回答
0
投票

你可以移动console.log(this.mainPage);来完成这样的() =>{},你不能在课堂上的任何地方使用,因为订阅称为asynchronous

//get current route
 router.events.subscribe(endUrl => {
   if(endUrl instanceof NavigationEnd ){
     this.mainPage = endUrl.url;
         console.log(this.mainPage); //works perfectly
   }
 },
 ()=>{
     console.log(this.mainPage); //does not work, outputs undefined
 });
}
© www.soinside.com 2019 - 2024. All rights reserved.