【问题标题】:How to pass Objects between pages in Angular?如何在Angular中的页面之间传递对象?
【发布时间】:2022-01-19 18:55:19
【问题描述】:

我正在尝试在 Ionic Angular 应用程序的页面之间传递对象。 不幸的是,我还不知道该怎么做。 对象被传递到新打开的“详细信息”页面一次。但是,当返回初始“主页”页面时,对象不再被传递。

有人知道如何解决这个问题吗?

代码如下:

home.page.html


<ion-content>
  <div *ngIf="spaces">
    <ion-item-sliding *ngFor="let space of spaces | async;">
      <ion-item
        (click)="openspacedetailsPage(space)"
        routerDirection="forward"
        detail
      >
        <ion-icon name="ellipse-outline" start></ion-icon>
        <ion-label> &nbsp; {{ space.spaceName }} </ion-label>
      </ion-item>
    </ion-item-sliding>
  </div>

home.page.ts

  openspacedetailsPage(space) {
    this.dataService.setSpace(space);
    this.router.navigate(["tabs/space-details"]);
  }

data.service.ts

  setSpace(space) {
    this.space = space;
  }

space-details.page.ts

  ngOnInit() {
    this.space = this.dataService.space;
    this.spaceName = this.space.spaceName
  }

  pageBack() {
    this.space = {};
    this.userId = "";
    this.spaceId = "";
    this.spaceName = "";
    this.dataService.setSpace(undefined);
  }
}

【问题讨论】:

  • 只是猜测......但问题可能是页面没有被破坏,因此不会再次调用 oninit。您可能需要 ionViewWillEnterionViewDidEnter 生命周期挂钩。
  • 用 ionViewDidEnter 解决了。感谢您的帮助!

标签: html angular typescript ionic-framework


【解决方案1】:

您可以使用 QueryParms 来实现这一点。 主页.ts

  openspacedetailsPage(space) {
    this.dataService.setSpace(space);
    this.router.navigate(["tabs/space-details"],{queryParams: {space}});
  }

space-details.page.ts

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) { }
  ngOnInit() {
        this.route.queryParams
          .subscribe(params => {
            console.log(params); 
            this.space = params.space;
              }
        );
      }

【讨论】:

    【解决方案2】:

    这里是使用查询参数方法传递对象的方法。 有关详细信息,请查看以下链接。

    https://ionicacademy.com/pass-data-angular-router-ionic-4

    【讨论】:

      【解决方案3】:

      解决办法如下:

      space-details.page.ts

       ionViewDidEnter() {
          this.space = this.dataService.space;
          this.spaceName = this.space.spaceName;
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-07
        • 2013-03-15
        • 1970-01-01
        • 1970-01-01
        • 2011-09-21
        • 2020-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多