Daniel
Daniel

Reputation: 1755

How to listen changes in routing Angular?

I subscribed on changes in routing:

public ngOnInit() {
    this.subscription = this.activateRoute.params.subscribe(params => {
      this.language = params['id'];
    });

    console.log(this.language);
  }

But when I change route path by click link I can not see console.log(this.language);. It is not displayed. There are not errors.

Why?

Upvotes: 0

Views: 128

Answers (2)

samAlvin
samAlvin

Reputation: 1678

subscribe is asynchronous. The console.log() may be called before this this.language = params['id']; statement is called (We won't know the flow because it is asynchronous).

You should put console.log(this.language); in the function inside subscribe:

this.subscription = this.activateRoute.params.subscribe(params => {
  this.language = params['id'];
  console.log(this.language);
});

This will make sure that console.log(this.language); is called right after this.language = params['id'];, since both statement are synchronous.

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

Subscribe method is used to subscribe to messages that are sent to an observable.This is ASYNC function , So you have to print "this.language" value inside subscribe

 public ngOnInit() {
        this.subscription = this.activateRoute.params.subscribe(params => {
          this.language = params['id'];
            console.log(this.language);
        });


      }

Upvotes: 1

Related Questions