0

I have two pages A and B and navigation takes place from page A to page B.
On page B I inserted a button to go back:

import { Location } from '@angular/common';
...
this.location.back();  

Navigation works correctly, but I don't want the ngOnInit method in page A to be invoked again when I go back.
This is the method I use to navigate between the two pages:

this.router.navigate(['/pages/page-b', item_id]);

UPDATE:

I would not want the xxx method to be called because it makes database calls which in this case I would like to avoid

3
  • you could have a look at the RouteReuseStrategy Commented Jul 6, 2020 at 10:56
  • Why don't you use sessionStorage/localStorage with a flag visited = 0 || 1 Commented Jul 6, 2020 at 10:56
  • you can't stop calling ngOnInit. Have some event emitter from page B, based on that handle the inside logic of ngOnInit. Commented Jul 6, 2020 at 10:56

2 Answers 2

1

There is nothing much to be needed here. When you visit the ngOnInit() for the first time. You should turn the variable true, by declaring one more variable.

When you come back from page B. In your ngOnInit() just check the value of that variable. If its true, don't call the method used for api call.

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

Comments

1

If your intention is just to avoid a DB call as mentioned, you can try caching the result in your service

class Service {
  private _cachedData;

  public getData() {
    if (this._cachedData)
      return of(this._cachedData);
    return this.http.get('/api')
      .pipe(
        tap((res) => { this._cachedData = res; })
      );
  }
}

Make sure to use apt datatypes like dictionary if your api call has parameters

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.