首页 文章

Angular2路线包括id

提问于
浏览
3

在Angular2项目中,我努力使路由器正常工作 .

在我们的应用程序中,我们只有主页面,然后是项目专用页面 . 例如,用户使用指向的直接链接访问这些项目页面

http:/ourwebsite.com/#/project/b288ba45-3b41-4862-9fed-7271245b9c29

我想在 Headers 导航栏中创建指向给定组件的链接,即使用户在此之后回家 .

例如:用户转到他的项目,然后单击 Home ,我希望链接 See project 能够将用户重定向到他之前的精确项目 .

My Routes

export const ROUTES: Routes = [
  { path: 'home',  component: HomeComponent },
  { path: 'project/:uuid',  component: ProjectComponent },
  { path: '',   redirectTo: '/home', pathMatch: 'full' },
  { path: '**', component: PageNotFoundComponent  }
];

我的带有导航 Headers 的 app.component.html

<ul class="nav navbar-nav">
    <li><a [routerLink]="['/home']">Home</a></li>
    <li><a [routerLink]="['/project', uuid]">See a project</a></li
</ul>

我在 app.component.ts 尝试了这个:

import { Component, ViewEncapsulation, OnInit, OnDestroy } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { Observable, Subscription } from 'rxjs';
import 'rxjs/Rx';

@Component({
  selector: 'app-root',
  encapsulation: ViewEncapsulation.None,
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
  uuid: string;
  private subscription: Subscription;

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.subscription = this.route.params.subscribe(params => {
       this.uuid = params['uuid'];
       console.log('Route UUID', this.uuid);
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

但事实是 UUID 在控制台中打印为未定义,因为此路由可从外部链接直接访问 .

我可以从 project.component.ts 获取 UUID ,但如何将其传递到导航栏中的 routerLink 元素,该导航栏位于 app.component

使用评论解决方案:

我尝试使用 [routerLink]="['/project', {uuid: uuid}]" ,但生成的链接URL是:/#/ think; uuid = undefined

谢谢你的帮助 .

1 回答

  • 2

    如果一次只需要保存一个链接,则可以将 uuid 保存为全局变量,然后在生成链接时使用它 .

    您可以这样添加全局变量:

    1)创建一个新服务(让我们称之为"SharedService"),你保留全局变量(你还应该为它分配一个值,以便它被初始化) . 您还可以在那里保留更多全局变量 .

    shared.service.ts

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export class SharedService {
      public uuid: string = '';
    
      constructor() { }
    
    }
    

    2)将SharedService导入 app.tsapp.module.ts (但在文件系统中调用它)并将其添加到同一 app.tsapp.module.ts 文件中的提供者:

    providers: [SharedService]
    

    不要将SharedService添加到任何其他组件中的提供程序,因为它将再次初始化,当您只想拥有其中一个时,最终会得到全局变量的多个实例 .

    3)现在将SharedService导入到您想要使用全局变量的所有组件中,并将该服务添加到每个组件的构造函数中:

    set.component.ts

    constructor(private shared: SharedService) {
        this.shared.uuid = 'test';
     }
    

    get.component.ts

    constructor(private shared: SharedService) {
        console.log(this.shared.uuid);
     }
    

相关问题