2

How to re-fetch data after parameter change from: oglas/1 to oglas/2 by click, so when put URL and than click ENTER everything works, but when click on oglas/2 button when oglas/1 is rendered URL changes to oglas/2 but data is from oglas/1?

TS

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Post } from "../post.model";
import { ServerService } from "../server.service";

@Component({
  selector: "post",
  templateUrl: "./post.component.html",
  styleUrls: ["./post.component.css"]
})
export class PostComponent implements OnInit {
  post: Post[];

  constructor(
    private route: ActivatedRoute,
    private serverService: ServerService
  ) {}

  ngOnInit(): void {
    this.getPost();
  }

  getPost(): void {
    const id = +this.route.snapshot.paramMap.get("id");
    this.serverService.getPosts(id).subscribe(post => (this.post = post));
  }
}

Service

import { HttpClient } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { Post } from "./post.model";
import { User } from "./user.model";
import { Observable } from "rxjs";

@Injectable({ providedIn: "root" })
export class ServerService {
  usersUrl = "http://localhost:3000/users";
  postsUrl = "http://localhost:3000/posts";

  constructor(private http: HttpClient) {}

  getPosts(id: number | string): Observable<Post[]> {
    const url = `${this.postsUrl}/${id}`;
    return this.http.get<Post[]>(url);
  }

  getUser(id: number | string): Observable<User[]> {
    const url = `${this.usersUrl}/${id}`;
    return this.http.get<User[]>(url);
  }
}

10
  • Can you please share the routing module where you defined app routing? Commented May 22, 2019 at 21:37
  • App routing module codeshare.io/adb86B @MuhammadFaisal Commented May 22, 2019 at 21:40
  • You must use the following line of code if you want to refetch data on the same URL Commented May 22, 2019 at 21:48
  • imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})] Commented May 22, 2019 at 21:48
  • not working, it's same but just got hash in front Commented May 22, 2019 at 21:52

2 Answers 2

1

Since your are making an API call for data in ngOnInit(), requested data may not be available by the time your component loads. And Angular might be reusing the same instance of the component, making ngOnInit() to be called only once.

You can use Angular Resolvers to ensure that you have the required data before loading the component.

1) Create a route resolver to fetch the required data before loading the route.

PostDataResolver.ts:

// ... imports

@Injectable()
export class PostDataResolver implements Resolve<any> {

 constructor(private serverService: ServerService) {}

 resolve(route: ActivatedRouteSnapshot) {

   const id = route.paramMap.get('id');

   return this.serverService.getPosts(id);
 }
}   

2) Add this resolver to your routing module:

{ path: "oglas/:id", component: PostComponent, resolve: { postData: PostDataResolver }}

3) Then access the resolved data in your component.

PostComponent.ts:

export class PostComponent implements OnInit {
  post: Post[];

  constructor(
    private route: ActivatedRoute,
    private serverService: ServerService
  ) {}

  ngOnInit(): void {
    this.post = this.route.snapshot.data.postData;
  }
}

This ensures that you have the latest and appropriate data before the component loads.

Sign up to request clarification or add additional context in comments.

4 Comments

Still nothing...This is one component just want to re-render new data again after button click @Nikhil thank you for your effort
this.activeRoute.queryParams.subscribe(queryParams => { // do something with the query params }); this.activeRoute.params.subscribe(routeParams => { this.loadUserDetail(routeParams.id); }); ..........this code works just it's very slow
I don't see this code posted. Looks like another issue. I should be able to help if you can single out the current problem, and report what didn't work with my solution. Thanks.
I would post it....There is no issue everything renders fine, but want to fetch new data from database when click sidebar button to the same component...URL changes but data not...this code works but it is very slow codeshare.io/amvrzj @Nikhil
0

Got it...

import { Component, OnInit, OnChanges } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { Post } from "../post.model";
import { ServerService } from "../server.service";

@Component({
  selector: "post",
  templateUrl: "./post.component.html",
  styleUrls: ["./post.component.css"]
})
export class PostComponent implements OnInit {
  post: Post[];
  id: number;

  constructor(
    private route: ActivatedRoute,
    private serverService: ServerService
  ) {}

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      this.id = parseInt(params.get("id"));
      this.getPost(this.id);
    });
  }

  getPost(id: number): void {
    this.serverService.getPosts(id).subscribe(post => (this.post = post));
  }
}

This code re-fetch data to a component

ngOnInit(): void {
    this.route.paramMap.subscribe(params => {
      this.id = parseInt(params.get("id"));
      this.getPost(this.id);
    });
  }

Thank you all for your effort!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.