0
votes

in Angular I want to refresh one component from another component.

I saw this article

https://medium.com/@rakshitshah/refresh-angular-component-without-navigation-148a87c2de3f

which suggest to add

mySubscription: any;

Then to add following in the constructor of my component.

this.router.routeReuseStrategy.shouldReuseRoute = function () {
    return false;
};

this.mySubscription = this.router.events.subscribe((event) => {
if (event instanceof NavigationEnd) {
  // Trick the Router into believing it's last link wasn't previously loaded
  this.router.navigated = false;
  }
});

And make sure to unsubscribe to "mySubscription" like below

ngOnDestroy() {
 if (this.mySubscription) {
   this.mySubscription.unsubscribe();
 }
}

but I don't understand it because there is no information about in which component should I add this, and how to trigger the refresh on button click event.. If someone can help I will be so grateful !

1
Im not so sure this will actually solves your problem, do you need to refresh component B if you click a button on component A? If yes, then why you need to refresh it - Kalhan.Toress
@Kalhan.Toress I'm fetching protocols from my server and I render it in two component (I import the same service in both). But when I add a new protocol in component A, I want it to update also in component B without having to refresh the page - Yoël Zerbib

1 Answers

0
votes

So if you have two components let's say componentA and componentB and if you want some data sync between two component I'd go for a shared service

here is a example for you to understand the below explanation.

for EX: ill call it ProductService

export class ProductService {
  private _producturl = 'https://jsonplaceholder.typicode.com/users';
  private _addNewSubject = new Subject();
  private _addNew$ = this._addNewSubject.asObservable();

  constructor(private _http: Http) {}

  getproducts(): Observable < IProduct[] > {
    return this._http.get(this._producturl)
      .map((response: Response) => < IProduct[] > response.json())
      .do(data => console.log(JSON.stringify(data)));
  }

  public get addNew$() {
    return this._addNew$;
  }

  public addNew(newItem: IProduct) {
    this._addNewSubject.next(newItem);
  }
}

_addNewSubject is a subject, by subscribing to that subject both component can get latest data.

how to subscribe?

this._product.addNew$.subscribe(newItem => this.iproducts = [...this.iproducts, newItem]);

This subscribe will call when someone executes the addNew function in the service, and using newItem param you can get the data, that pushed inside the addNew function using this._addNewSubject.next(newItem);