Angular上一页的ngOnInit方法的导航问题
Angular navigation problem with the ngOnInit method of the previous page
我有两个页面 A 和 B,导航是从页面 A 到页面 B。
在页面 B 我插入了一个返回按钮:
import { Location } from '@angular/common';
...
this.location.back();
导航正常,但不想返回时再次调用A页面的ngOnInit方法
这是我用来在两个页面之间导航的方法:
this.router.navigate(['/pages/page-b', item_id]);
更新:
我不希望调用 xxx 方法,因为它会进行数据库调用,在这种情况下我想避免这种情况
如果您的目的只是为了避免上述的数据库调用,您可以尝试在您的服务中缓存结果
class Service {
private _cachedData;
public getData() {
if (this._cachedData)
return of(this._cachedData);
return this.http.get('/api')
.pipe(
tap((res) => { this._cachedData = res; })
);
}
}
如果您的 api 调用有参数
,请确保使用像字典这样的适当数据类型
这里没有什么需要的。当您第一次访问 ngOnInit()
时。您应该通过再声明一个变量来将变量变为真。
当您从页面 B 返回时。在您的 ngOnInit()
中检查该变量的值。如果它 true
,请不要调用用于 api 调用的方法。
我有两个页面 A 和 B,导航是从页面 A 到页面 B。
在页面 B 我插入了一个返回按钮:
import { Location } from '@angular/common';
...
this.location.back();
导航正常,但不想返回时再次调用A页面的ngOnInit方法
这是我用来在两个页面之间导航的方法:
this.router.navigate(['/pages/page-b', item_id]);
更新:
我不希望调用 xxx 方法,因为它会进行数据库调用,在这种情况下我想避免这种情况
如果您的目的只是为了避免上述的数据库调用,您可以尝试在您的服务中缓存结果
class Service {
private _cachedData;
public getData() {
if (this._cachedData)
return of(this._cachedData);
return this.http.get('/api')
.pipe(
tap((res) => { this._cachedData = res; })
);
}
}
如果您的 api 调用有参数
,请确保使用像字典这样的适当数据类型这里没有什么需要的。当您第一次访问 ngOnInit()
时。您应该通过再声明一个变量来将变量变为真。
当您从页面 B 返回时。在您的 ngOnInit()
中检查该变量的值。如果它 true
,请不要调用用于 api 调用的方法。