如何获取订阅外的价值?

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

我想获取之前的路由并在 HTML 文件中打印它的值。但什么也没有打印出来。在订阅之外该值仍然为空。

这是我的代码片段:

TS文件:

 @Component({
  selector: 'app-transaction-details-payments',
  templateUrl: './transaction-details.component.html',
  styleUrls: ['./transaction-details.component.css']
})
 previousUrl: any = null;

ngOnInit(){
    this.router.events.pipe(
          filter((event) => event instanceof NavigationEnd)
        ).subscribe((event: NavigationEnd) => {
          this.previousUrl = this.currentUrl;
          this.currentUrl = event.url;
          this.urlService.setPreviousUrl(this.previousUrl);
 
this.getPrevUrl();
        });
    }

getPrevUrl(){
    console.log(this.previousUrl) //getting the correct value but this value is not getting printed in HTML.
}

HTML代码:

<p>{{previousUrl}}</p>
angular routes navigation
1个回答
0
投票

看起来您正在尝试打印之前的 URL,但在订阅之外它仍然显示为 null。我认为问题可能是 console.log 语句在订阅有机会更新 previousUrl 值之前运行。

也许尝试将 console.log 移到订阅内?这是对您的代码的快速调整:

previousUrl: any = null;

this.router.events.pipe(
filter((event) => event instanceof NavigationEnd)
).subscribe((event: NavigationEnd) => {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
this.urlService.setPreviousUrl(this.previousUrl);
console.log(this.previousUrl);  // should print the previous URL now
});
© www.soinside.com 2019 - 2024. All rights reserved.