通过Angular 2路径传递动态数据

时间:2016-12-12 06:38:27

标签: angular typescript angular2-routing

可以将静态数据传递给Angular 2路由而不在URL上显示。

但是如何以相同的方式传递动态数据/对象?

4 个答案:

答案 0 :(得分:4)

您可以使用解析器。解析器返回的数据可用于路由配置上静态data的路由

有关示例,请参阅https://angular.io/guide/router#resolve-guard

@Injectable()
export class CrisisDetailResolve implements Resolve<Crisis> {
  constructor(private cs: CrisisService, private router: Router) {}
  resolve(route: ActivatedRouteSnapshot): Promise<Crisis>|boolean {
    let id = route.params['id'];
    return this.cs.getCrisis(id).then(crisis => {
      if (crisis) {
        return crisis;
      } else { // id not found
        this.router.navigate(['/crisis-center']);
        return false;
      }
    });
  }
}
path: '',
component: CrisisListComponent,
children: [
  {
    path: ':id',
    component: CrisisDetailComponent,
    canDeactivate: [CanDeactivateGuard],
    resolve: {
      crisis: CrisisDetailResolve
    }
  },
ngOnInit() {
  this.route.data
    .subscribe((data: { crisis: Crisis }) => {
      this.editName = data.crisis.name;
      this.crisis = data.crisis;
    });
}

答案 1 :(得分:1)

你可以做两件事 1.不推荐但使用数据作为路由器参数并传递,

{ path: 'some:data', component: SomeComonent }

并用作

let data = {"key":"value"}
this.router.navigate(['/some', data)

2.而不是通过路径参数传递数据(因为数据可能很大并且也容易受到攻击,因为它可以被用户调整)

@Injectable()
export class SomeService {
  data = {};
}

@Component({...
   providers: [SomeService]
export class Parent {
  constructor(private someService:SomeService) {}

  private click() {
    this.someService.data = {"key":"value"}
  }
}

答案 2 :(得分:1)

最好结合以上两个答案:

  • GünterZöchbauer的answer由一个自定义的解析器组成,该解析器是message enricher:给定以/crisis/15结尾的URL,它将把危机的全部数据传递给CrisisComponent。我们需要解析器,但是我认为OP不想在URL中显示任何数据。
  • Tsadkan Yitbarek的answer提出了一项用于数据存储和通信的服务(类似于Redux / Flux中的Store)。他正确地认为这太过分了,但是我们需要将信息存储在某个地方。

因此,解决方案是将共享数据放入Resolver本身:与组件不同,服务是长期存在的,并且始终只有一个实例,因此数据在resolver中是安全的:

// --- CrisisDetailResolve --- 
// In the function body, add:
private currentCrisisId: number | string

set(crisisId: number | string) {
   this.currentCrisisId = crisisId 
}

// change line 5 of CrisisDetailResolve:
 let id: number = 0 + this.currentCrisisId

// -- In your code -- 
// You can now navigate while hiding 
// the crisis number from the user:
private click(crisisId : string | number) {
  // tell resolver about the upcoming crisis:
  this.crisisResolve.set(crisisId)  
  // navigate to CrisisDetail, via CrisisResolve:
  this.router.navigate(['/crisisDetail')
  // CrisisDetail can now receive id and name in its NgOnInit via `data`,
  // as in Günter Zöchbauer's answer and the Angular docs 
}

另请参阅Angular Docs on Routing

答案 3 :(得分:0)

您可以使用状态对象从Angular7.2中传递动态数据

在Component中,使用navigationByUrl发送任何数据

  public product = { id:'1', name:"Angular"};
  gotoDynamic() {
     this.router.navigateByUrl('/dynamic', { state: this.product });
  }

并使用history.state读取它

In dynamicComponent

    ngOnInit() {
           this.product=history.state;
    }  

参考: Passing Dynamic Data