typescript 通过 Angular 2 路由传递动态数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41095349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 04:04:30  来源:igfitidea点击:

Passing dynamic data through Angular 2 route

angulartypescriptangular2-routing

提问by Kaleab

It is possible to pass static data to an Angular 2 route without showing it on the URL.

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

But how can I pass dynamicdata/object in the same way?

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

采纳答案by Günter Z?chbauer

You can use a resolver. The data returned by a resolver is made available to routes the same way static dataon route configurations is

您可以使用解析器。解析器返回的数据可用于路由,就像静态data路由配置一样

For an example see https://angular.io/guide/router#resolve-guard

有关示例,请参阅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;
      }
    });
  }
}
@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
    }
  },
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;
    });
}
ngOnInit() {
  this.route.data
    .subscribe((data: { crisis: Crisis }) => {
      this.editName = data.crisis.name;
      this.crisis = data.crisis;
    });
}

回答by tsadkan yitbarek

You can do two things 1.Not recommended but use data as router parameter and pass,

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

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

and use as

并用作

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

2.Instead of passing data through route params(because data may be huge and also vulnerable to attack since it can be viwed by the user)

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

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

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

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

回答by dirkjot

It is best to combine the previous two answers:

最好结合前两个答案:

  • Günter Z?chbauer's answerconsists of a custom Resolver which is an message enricher: Given an URL ending in /crisis/15, it will pass the full data of the crisis to the CrisisComponent. We need the Resolver, but I think OP did not want any data to show in the URL.
  • Tsadkan Yitbarek's answerproposes a service for data storage and communication (similar to a Store in Redux/Flux). He rightly thinks this is overkill, but we need to store the information somewhere.
  • Günter Z?chbauer 的回答包含一个自定义的 Resolver,它是一个消息丰富器:给定一个以 结尾的 URL /crisis/15,它将把危机的完整数据传递给 CrisisComponent。我们需要解析器,但我认为 OP 不希望在 URL 中显示任何数据。
  • Tsadkan Yitbarek 的回答提出了一种用于数据存储和通信的服务(类似于 Redux/Flux 中的 Store)。他正确地认为这是矫枉过正,但我​​们需要将信息存储在某个地方。

The solution therefore is to put the shared data in the Resolver itself: Unlike components, services are long-lived and always have only one instance so the data is safe in the 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 
}

See also Angular Docs on Routing

另请参阅有关路由的 Angular 文档

回答by vcs

You can pass the dynamic data from the Angular7.2 using the state object

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

In Component send any data using navigateByUrl

在组件中使用navigateByUrl发送任何数据

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

And read it using history.state

并使用 history.state 阅读它

In dynamicComponent

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

Reference: Passing Dynamic Data

参考: 传递动态数据