How to get the value outside the subscription?

I want to get the previous route and print it’s value in the HTML file. But nothing is getting printed. The value is still null outside the subscription.

This is my code snippet:

TS file:

 @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 code:

<p>{{previousUrl}}</p>

7

it looks like you’re trying to print the previous URL, but it’s still coming up as null outside the subscription. I think the problem might be that the console.log statement is running before the subscription has a chance to update the previousUrl value.

Maybe try moving the console.log inside the subscription? Here’s a quick tweak to your code:

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
});

2

Your subscription callback is executed asynchronously, but the rendering of the template access the value before that happens.

One approach would be to use a observable eg:

Component:

 @Component({
  selector: 'app-transaction-details-payments',
  templateUrl: './transaction-details.component.html',
  styleUrls: ['./transaction-details.component.css']
})
 previousUrl$ = new BehaviorSubject<string | null>(null);

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

    async getPrevUrl(){
        return firstValueFrom(this.previousUrl$);
    }
}

Template:

<p>{{previousUrl$ | async}}</p>

Every time when the previousUrl$ observable emits a new value, every subscriber get’s notified about the change.

I’ve tried creating a service and moved my code to the service and used it inside my component and it worked.

Here is my code:

Service:

 @Injectable({
      providedIn: 'root'
    })
export class UrlService {
  private previousUrlUpdated: string;
  private currentUrl: string;

  constructor(private router: Router) {
    this.currentUrl = this.router.url;
    router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        console.log(event)
        this.previousUrlUpdated = this.currentUrl;
        this.currentUrl = event.url;
      };
    });
  }

  public getPreviousUrl() {
    return this.previousUrlUpdated;
  }
}

ts:

this.previousUrl = this.urlService.getPreviousUrl();

As per me Subscribe is an async process so your HTML is loading before your subscribe =>get completed.
hence it is not printing in HTML but getting printed in console because its executing once the subscribe is completed

TRY This :
TS file :
previousUrl: any; // remove null
HTML code:

<p *ngIf="previousUrl">{{previousUrl}}</p>

or <div *ngIf="previousUrl"><p>{{previousUrl}}</p></div>

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật