有没有一种方法可以将对象作为navigationParam传递?

时间:2019-09-18 00:22:01

标签: angular typescript firebase ionic4

This is a screenshot of the console log

gotomsg和go2msg是我要记录的两个对象,然后再将它们发送到要导航的页面。

  goToMessagePage(itinerary) {
    let myItin = this.findMyItinerary(itinerary.id);
    console.log('gotomsg', myItin);
    console.log('go2Msg', itinerary);

    const navigationParam: NavigationExtras = {
      queryParams: {
        theirItinerary: itinerary,
        myItinerary: myItin
      }
    };
    this.router.navigate(['messages'], navigationParam);
  }

导航到“消息”页面后,我在[object Object]中获得了2个对象,但是当我尝试访问该对象的任何属性(如object.id)时,都会得到“ undefined”。

  constructor(public messageService: MessagesService,
              private route: ActivatedRoute) {

    this.route.queryParams.subscribe(params => {
      this.theirItinerary = params['theirItinerary'];
      this.myItinerary = params['theirItinerary'];
      console.log('Myitinerary message', this.myItinerary.data());
      console.log('theirItin message', this.theirItinerary.data());
    });
  }

是否可以获取作为导航参数传递的对象的值?

1 个答案:

答案 0 :(得分:1)

尝试使用JSON.stringify

  goToMessagePage(itinerary) {
    let myItin = this.findMyItinerary(itinerary.id);
    console.log('gotomsg', myItin);
    console.log('go2Msg', itinerary);

    const navigationParam: NavigationExtras = {
      queryParams: {
        theirItinerary: itinerary,
        myItinerary: JSON.stringify(myItin),
      },
    };
    this.router.navigate(['messages'], navigationParam);
  }

或使用state

  goToMessagePage(itinerary) {
    let myItin = this.findMyItinerary(itinerary.id);
    console.log('gotomsg', myItin);
    console.log('go2Msg', itinerary);

    const navigationParam: NavigationExtras = {
      queryParams: {
        theirItinerary: itinerary,
      },
      state: {
        myItinerary: myItin,
      },
    };
    this.router.navigate(['messages'], navigationParam);
  }

消息部分:

  constructor(
    private router: Router,
  ) {
    const navigation = this.router.getCurrentNavigation();
    console.log(navigation.extras.state);
  }