0

I want to refresh a page (through this.navigate.url) when a promise is executed but I can't seem to make it work.

import {Router} from '@angular/router';

constructor(public router: Router) {
}

myPromise('/api/users').then((response) => {
    return response.json();
}).then(function (response) {
    this.router.navigate.url([url]);
});

I even tried window.location.reload and it doesn't work either.

Basit
  • 1,830
  • 2
  • 31
  • 50
  • 1
    What is `this` here? What does `this.navigate` do? Where does `url` come from? What does the console show? –  May 26 '17 at 06:30
  • Do you want to navigate inside your app with the help of the Angular router och to an external site? If external, try `window.location.replace("http://something.com");` – Fredrik Lundin May 26 '17 at 06:32
  • @torazaburo I edited my question to elaborate further. router is an instance of Router class, url is current page URL. What I want is to refresh my current page after a promise is executed. – Basit May 26 '17 at 06:35
  • @FredrikLundin I want to refresh my page once a promise is successfully executed. – Basit May 26 '17 at 06:35
  • @torazaburo is there a refer to correct this answer for typescript/angular? Like: https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback – eko May 26 '17 at 06:36
  • Possible duplicate of [Navigating to the same route not refreshing the component?](https://stackoverflow.com/questions/38127308/navigating-to-the-same-route-not-refreshing-the-component) – eko May 26 '17 at 11:03
  • I went through that particular question before creating mine. My URL isn't changing and nor do I want it to. I just need to perform a page reload after my promise is executed. – Basit May 26 '17 at 11:05

2 Answers2

2
constructor(private zone:NgZone) {}

this.zone.run(() => this.router.navigate(['main']));



//import NgZone from angular core, use zone.run inside the promise 
v8-E
  • 1,077
  • 2
  • 14
  • 21
  • 2
    Welcome to StackOverflow. Some explanation would greatly improve the quality of the answer and help other users who may encounter similar problems in the future Please take some time to read the help page https://stackoverflow.com/help/how-to-answer – v8-E Aug 08 '18 at 10:37
1

Angular 6.0 Router link is always disabled in child component.

Router link is always disabled in child component, if our navigation code is inside promise. To solve this issue we can use NgZone inside promise.

Let me show you the file contents:

login.component.ts

import { NgZone } from '@angular/core'; //import ngZone from angular core

constructor(private zone:NgZone) {}

authorize(): Promise<any> {
return new Promise((resolve, reject) => {
  let promise = this.auth2.signIn();
  promise.then(() => {
    let self = this;
    let profile = this.auth2.currentUser.get().getBasicProfile();
    this.authenticationService.login(profile);
    this.zone.run(() => this.router.navigate(['/contacts']));
  });
});
}