0

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?

onetwo12
  • 2,359
  • 5
  • 23
  • 34
Daniel
  • 1,695
  • 6
  • 23
  • 41
  • Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – eko Jul 27 '17 at 08:11
  • 1
    just move `console.log` inside `params=>{...} function` – Max Koretskyi Jul 27 '17 at 08:13

2 Answers2

1

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


      }
Balachandran
  • 9,567
  • 1
  • 16
  • 26
  • May be problem in routing: I have path URL: `http://localhost:3000/#/language/en` and it changed. – Daniel Jul 27 '17 at 08:14
0

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.

samAlvin
  • 1,648
  • 1
  • 11
  • 35
  • 2
    @Daniel try `console.log(params)` does your `params` variable even have an `id` property? – eko Jul 27 '17 at 08:15
  • @Daniel Look in your appModule where you register your path urls, does it have something like this: `/{yourUri}/:id` ... In order to get the `params['id']`, your path url should have this `:id` part – samAlvin Jul 27 '17 at 08:17
  • 1
    In routing I have: `{ path: 'language/:id', component: LanguageComponent },` – Daniel Jul 27 '17 at 08:18
  • `console.log(params);` is empty object when component is initialized – Daniel Jul 27 '17 at 08:19