我正在使用星云框架,来自akveo的优秀团队。
其中一个组件是上下文菜单,它创建了一个弹出菜单,其中包含从阵列读取的选项
items = [{ title: 'Profile' }, { title: 'Log out' }];
我想导航到另一个屏幕,但教程主要讨论routerLink
<p>This is my link <a routerLink="/getMeOut">out</a></p>
但在这种情况下,我不能添加<a>
标记,因为它们抽象了点击事件,并允许您像一样订阅
this.menuService.onItemClick()
.pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title),
)
.subscribe(title => {
console.error(`${title} was clicked!`)
});
点击每个按钮时都会打印出来,但我必须触发.subscribe()
函数内部的导航。
如何做到这一点?
首先,在一些路由模块中,外部路由必须存在
// app-routing.module.ts
const routes: Routes = [
{ path: 'getMeOut', component: OutComponent },
..
]
需要四件事
- 从
@angular/router
导入路由器 - 在构造函数
private router: Router
中创建一个专用路由器 - 使用所需路由呼叫
navigateByUrl()
- 使用
nbContextMenuTag
属性标识上下文菜单
然后,在保存上下文菜单的模块中,我们创建路由器来处理类似的导航
// awesome.component.ts
import { Router } from '@angular/router'
import { NbMenuService } from '@nebular/theme';
@Component({
selector: 'awesome',
styleUrls: ['./awesome.component.scss'],
templateUrl: './awesome.component.html',
})
ngOnInit() {
this.menuService.onItemClick()
.pipe(
filter(({ tag }) => tag === 'my-context-menu'),
map(({ item: { title } }) => title),
)
.subscribe(title => {
if (title === 'Log out') this.router.navigateByUrl('/getMeOut');
console.error(`${title} was clicked!`)
});
}
constructor(
private menuService: NbMenuService,
private router: Router) {
}
请参阅@angular/router
中navigateByUrl的简单使用。
只需将nbContextMenuTag="my-context-menu"
添加到html模板
<nb-action *nbIsGranted="['view', 'user']" >
<nb-user nbContextMenuTag="my-context-menu"></nb-user>
</nb-action>
我希望这不是一个骗局。我找到了这个答案,但这意味着更多的是嵌套路由器。