Angular2路线包括id

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

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

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

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

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

例如:用户转到他的项目,然后单击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  }
];

我的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

谢谢你的帮助。

angular angular2-routing
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);
 }
© www.soinside.com 2019 - 2024. All rights reserved.