我是IONIC 4的新手,我想将对象从一个屏幕传递到另一个屏幕。我的第一个屏幕是screen1,我想将类型为“ any”的“模型”对象从screen1传递到screen2。
当前,我正在使用以下代码从screen1导航到screen2。
this.router.navigateByUrl('screen2 /');
如何通过此路线传递“模型”对象?
我在Google上搜索了解决方案,但没有发现与我的问题相关的任何内容。我只是发现只有一件事,我们可以使用queryparams通过URL传递数据,但是我想保持数据私密,并且不想在URL中显示数据。
任何人都知道,我该怎么做?
答案 0 :(得分:1)
我对您的建议是实施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;
}
}
答案 1 :(得分:0)
您只需使用路由器导航即可完成
this.router.navigate(['screen2', {modelName: model}]);
并通过ActivatedRoute接收
this.activatedRoute.snapshot.paramMap.get('modelName');
答案 2 :(得分:0)
由于您的问题是“如何将内容从一页发送到另一页”,因此解决方案不必局限于使用路由器:另一种选择是使用存储。
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);
});
只需将它扔在那里。我的应用程序的结构非常有用。该项目将一直保留在存储中,直到您删除它为止。也可能有用,或者没有。我想取决于您的需要!希望它有用。