我有两个页面,我希望对这两个路径中的每一个都使用相同的组件。原因是我共享了头,它有两个主组件的搜索字段。每当我更改页面时,我都会收到对该服务的额外调用。第一次2次,第二次4次,第三次6次……我只想让页面重新开始。这就是构造函数正在发生的事情。我所要做的就是根据路由url显示/隐藏库和详细信息页面。
this.router.events.subscribe((val) => {
if (val instanceof NavigationEnd) {
let urlArray = val.url.split('/');
if (urlArray[1] === 'library') {
this.detail = false;
} else if (urlArray[1] === 'detail') {
this.searchById(urlArray[2]);
}
}
});
基本上,库组件有一个图书列表,当单击该列表时,将转到该图书的详细信息页面。我显示/隐藏库和详细页
const appRoutes: Routes = [
{ path: 'library', component: LibraryComponent },
{ path: 'detail/:id', component: LibraryComponent },
{ path: '', redirectTo: '/library', pathMatch: 'full' }
];
这是服务调用,它只返回dummyJSON数据
searchById(id) {
this.mainService.searchById(id).subscribe(
data => { this.detail = true; this.bookdata = data; console.log(data); },
err => { },
() => { }
)};
发布于 2019-07-31 14:05:46
在路由器事件返回后,我刚刚取消订阅它。
const routerEvent = this.router.events.subscribe((val) => {
if (val instanceof NavigationEnd) {
let urlArray = val.url.split('/');
if (urlArray[1] === 'library') {
this.detail = false;
} else if (urlArray[1] === 'detail') {
this.searchById(urlArray[2]);
}
routerEvent.unsubscribe();
}
});
发布于 2019-07-30 20:18:51
您的代码中存在订阅漏洞,请将其更改为下面的内容
private unsubscribeAll: Subject<any> = new Subject<any>();
ngOnDetroy() {
this.unsubscribeAll.next();
this.unsubscribeAll.complete();
}
...
this.mainService.searchById(id)
.pipe(
takeUntil(this.unsubscribeAll)
)
.subscribe(
data => { this.detail = true; this.bookdata = data; console.log(data); },
err => { },
() => { }
);
...
https://stackoverflow.com/questions/57279073
复制相似问题