【问题标题】:Pass object with route ionic 4使用路线 ionic 4 传递对象
【发布时间】:2019-06-03 23:11:18
【问题描述】:

我是 IONIC 4 的新手,我想将一个对象从一个屏幕传递到另一个屏幕。我的第一个屏幕是 screen1,我想将“any”类型的“模型”对象从 screen1 传递到 screen2。

目前我正在使用以下代码从我的屏幕 1 导航到屏幕 2。

this.router.navigateByUrl('screen2/');

我怎样才能通过这条路线传递“模型”对象?

我在 google 上搜索了解决方案,但没有发现任何与我的问题相关的内容。我刚刚发现只有一件事我们可以使用查询参数通过 URL 传递数据,但我想保持数据私有并且不想在 URL 中显示数据。

谁知道,我该怎么做?

【问题讨论】:

    标签: angular typescript ionic-framework routes ionic4


    【解决方案1】:

    由于您的问题是“我如何将内容从一个页面发送到另一个页面”,因此解决方案不必局限于使用路由器:另一种选择是使用存储。

    import { Router } from '@angular/router';
    import { Storage } from '@ionic/storage';
    
    blah() {
        this.storage.set('importantThing', this.importantThing);
        this.router.navigateByUrl('my-page/new-subpage');
    }
    

    然后在接收页面:

    await this.storage.get('importantThing').then(result => {
          this.importantThing= result;
          console.log('my importantThing is', this.importantThing);
        });
    

    只是把它扔在那里作为替代品。我的应用程序的结构方式非常有用。该项目将在存储中保留在幕后,直到您将其删除。也可能有用,也可能没有。取决于你需要什么,我想!希望有用。

    【讨论】:

      【解决方案2】:

      你可以简单地使用路由器导航来做到这一点

          this.router.navigate(['screen2', {modelName: model}]);
      

      并通过ActivatedRoute接收

          this.activatedRoute.snapshot.paramMap.get('modelName');
      

      【讨论】:

        【解决方案3】:

        我给你的建议是实现resolver

        看看我在 StackBlitz 的 DEMO 看看它的实际效果

        实现解析器:

        @Injectable()
        class TeamResolver implements Resolve<Team> {
          constructor(private myService: MyService) {}
        
          resolve(
            route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot
          ): Observable<any>|Promise<any>|any {
            // return the data you need in your component using your service 
            // route params will sit in - route.params.id
          }
        }
        

        声明:

        @NgModule({
          imports: [
            RouterModule.forRoot([
              {
                path: 'team/:id',
                component: TeamCmp,
                resolve: {
                  team: TeamResolver
                }
              }
            ])
          ],
          providers: [TeamResolver]
        })
        class AppModule {}
        

        使用它:

        @Component({
          ...
        })
        export class TeamCmp {
          constructor(private activatedRoute: ActivatedRoute) {
            // the data sits here - this.activatedRoute.snapshot.data;
          }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-08-30
          • 1970-01-01
          • 2018-07-16
          • 2019-09-16
          • 2016-06-22
          • 1970-01-01
          • 2020-04-20
          • 2017-09-30
          相关资源
          最近更新 更多