Home > database >  Refreshing the page after changing the URL
Refreshing the page after changing the URL

Time:03-26

It seems to be a basic thing but I'm struggling. I have a view "/plugin/{pluginId}" that doesn't update when I hit enter after changing the pluginId in the address bar. I have to manually refresh the page in the browser. What can I do so that it refreshes automatically?

<div>
    <div>
        <a mat-raised-button href="/plugin">
            <span>&#8592;</span>
        </a>
        <a mat-raised-button href="" style="float: right">Send message</a>
    </div>
    <div>
        <ul>       
            <li *ngFor="let message of (messages$ | async)">
                {{message.message}}
            <br><br>
        </li></ul>
    </div>
</div>
export class Foo implements OnInit {
  pluginMessagesState$: Observable< fromPluginMessages.State >;
  pluginId = '';
  messages$: Observable< Message[] >;

  constructor(private route: ActivatedRoute,
              private store: Store< fromRoot.State >,

  ) {
    if ( this.route.snapshot.params[ 'pluginId' ] ) {
      this.pluginId = this.route.snapshot.params[ 'pluginId' ];
    }

    this.pluginMessagesState$ = this.store.select( fromRoot.getPluginMessagesState );
    this.messages$ = this.pluginMessagesState$.pipe(
      map( state => state.pluginMessages.get( this.pluginId )?.list || [] )
    );
  }

  ngOnInit(): void {
  }

}

CodePudding user response:

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

@Component({
  selector: 'app-user-detail',
  templateUrl: 'user-detail.component.html'
})
export class UserDetailComponent implements OnInit {
    constructor(private activeRoute: ActivatedRoute) {
    }

    ngOnInit() {
        const queryParams = this.activeRoute.snapshot.queryParams
        const routeParams = this.activeRoute.snapshot.params;

        // do something with the parameters
        this.loadUserDetail(routeParams.id);
    }
}

or

ngOnInit() {
    this.activeRoute.queryParams.subscribe(queryParams => {
        // do something with the query params
    });
    this.activeRoute.params.subscribe(routeParams => {
        this.loadUserDetail(routeParams.id);
    });
}

CodePudding user response:

Does your router file look like this ?

{path: 'plugin/:id', component: UserDetailComponent}

If so, subscribe to ActivatedRoute (inject it in the constructor parameters) like this:

public pluginId: number;
constructor(private route: ActivatedRoute) {
}

And access the parameter by subscribing to route.params:

ngOnInit() {
  this.routeSub = this.route.params.subscribe(params => {
      // update the pluginId accordingly
      this.pluginId = params['id'];
  });
}
  • Related