passing data using router

后端 未结 2 1306
庸人自扰
庸人自扰 2021-01-16 04:04

I have a problem with passing data to other component. Here is the example.

 onEdit(data) {
    this.router.navigate([\"/edit\", { state: data }], {
      re         


        
2条回答
  •  伪装坚强ぢ
    2021-01-16 04:42

    I think you need to change your routing to something like below,

    you can use QueryParams for your scenario

     this.router.navigate(["/edit"], { 
          queryParams: { dataParam : value, dataPara2: value }
     });
    

    get the value by subscribing to ActivatedRoute in Component.

    this.route.queryParams.subscribe(params => {
         console.log(params['dataParam '],params['dataPara2']);
    });
    

    you can also remove the data param in Routing initialization.

    Edit

    If you have already a common service use that otherwise create service class like below,

    export class ServiceName {
        private data = new BehaviorSubject([]);
    
        getData(): Observable {
            return this.data.asObservable();
        }
    
        setData(param: any): void {
            this.data.next(param);
        }
      }
    

    then you can call the data methods in component before navigating the router, and get the data with getData() method.

      this.service.setData(data);
      this.router.navigate(["/edit", { state: data }], {
          relativeTo: this.activatedRoute
      });
    

    Hope this helps.. :)

提交回复
热议问题