如何通过Angular中的服务激活路由?

问题描述 投票:1回答:2

我创建了一个角度应用程序,我将“欢迎页面”组件设置为默认路由,因此它是第一个在用户访问该站点时弹出的组件。在该组件中,我有链接需要激活app组件中的router-outlet。看到“欢迎页面组件”被路由器插座拉入,我认为我必须使用服务来检测点击的链接并更新应用程序组件中的路由,因为两个组件之间没有任何明确的通过它除此以外。

我创建了一个看起来像这样的服务文件

@Injectable()

export class RouteService{

    public clickedLink: Subject<string> = new Subject<string>();

    setLink(link: string){ this.clickedLink.next(link); }
}

我将“欢迎页面组件”修改为这样

export class WelcomePageComponent {

    constructor(private RS: RouteService ){}

    sendLink(link: string){ this.RS.setLink(link); }
}

然后将模板中的链接修改为此

<a (click)="sendLink('/illustration')"></a>

然后在app组件中我有这个

export class AppComponent implements OnInit {

    pageLink: string;

    constructor( private RS: RouteService, private router: Router ){}

    ngOnInit(){
       this.RS.clickedLink.subscribe(link => this.pageLink = link); 
    }

    pageNav(link:string){ this.router.navitgate(link); }
}

现在我一直在搞清楚如何触发pageNav()函数来更新路线。我试着听@HostListener试图听pageLink变量和一点点可观察量,但似乎找不到任何与我想要实现的相关的东西。有人能帮忙吗?

UPDATE

我的app.module看起来像这样

@NgModule({
  declarations: [
      AppComponent
  ],
  imports: [
      BrowserModule,
      AppRoutingModule,
      PagesModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

PagesModule是我为“页面组件”启动的模块,看起来像这样

@NgModule({
    imports: [ BrowserModule ],
    declarations: [
        WelcomePageComponent, IllustrationPageComponent
    ],
    exports: [
        WelcomePageComponent, IllustrationPageComponent
    ]
})

export class PagesModule{}

AppRoutingModule看起来像这样

export const routes: Routes = [
    { path: '', redirectTo: '/welcome', pathMatch: 'full' },
    { path: 'welcome',      component: WelcomePageComponent },
    { path: 'illustration', component: IllustrationPageComponent }
]

@NgModule({
    imports: [
        RouterModule.forRoot(routes)
    ],
    exports: [
        RouterModule
    ]
})

export class AppRoutingModule {}
angular typescript
2个回答
1
投票

您可以通过以下步骤解决问题:

  • 目前您已经通过订阅clickedLink来收听点击。单击链接时,将新链接保存在“pageLink”中,但您可以执行更多操作(例如,调用pageNav())。 如果直接调用pageNav(链接),则不再需要pageLink。 this.RS.clickedLink.subscribe(link => { this.pageNav(link); });
  • 确保为“RouterService”使用单件服务。具有不同的实例将不允许您跨组件发出事件。为此:仅在组件的父模块上提供服务。 (从组件提供者列表中删除它)
  • router.navigate()需要一个数组,因此您可以像这样使用它:this.router.navigate([link]);

0
投票

我不确定如果我完全理解你的问题,但角度路由非常容易配置和实现。只需将routerLink指令添加到任何元素,它将在单击时更新路由器插座。这是一个例子

<nav>
    <a routerLink="/dashboard">
       dashboard
    </a>
    <a routerLink="/path-to-another-component">
       new componenet
    </a>
</nav>

路由器链接指令调用场景后面的角度路由服务,检查路由器配置是否找到要呈现的组件并更新路由器插座。

这里没有必要观察。我希望能帮助你。

© www.soinside.com 2019 - 2024. All rights reserved.