Passing dynamic data through Angular 2 route

和自甴很熟 提交于 2019-12-09 15:08:38

问题


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

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


回答1:


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

For an example see 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;
    });
}



回答2:


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

{ 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)

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

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

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



回答3:


It is best to combine the previous two answers:

  • Günter Zöchbauer's answer consists 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 answer proposes 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.

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




回答4:


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

In Component send any data using navigateByUrl

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

And read it using history.state

In dynamicComponent

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

Reference: Passing Dynamic Data



来源:https://stackoverflow.com/questions/41095349/passing-dynamic-data-through-angular-2-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!