Ionic 4. NavParams的替代品

7gu*_*uyo 3 ionic-framework

我正在使用离子4。它不接受使用navparams接收数据。这是我的发件人页面方法:

  //private route:Router
  gotoFinalView(intent) {
    this.route.navigateByUrl(`${intent}`, this.destination);
  }
Run Code Online (Sandbox Code Playgroud)

收件人页面行;

  //private navParams:NavParams  
  this.destination = navParams.data;
Run Code Online (Sandbox Code Playgroud)

在ionic 4中执行此操作的正确方法是什么。我也不确定gotoFinalView方法是否有效。

7gu*_*uyo 5

这是我解决问题的方式:

我创建了一个带有setter和getter方法的Service;

import { Injectable } from "@angular/core";

@Injectable({
  providedIn: "root"
})
export class MasterDetailService {
  private destn: any;
  constructor() {}

  public setDestn(destn) {
    this.destn = destn;
  }

  getDestn() {
    return this.destn;
  }
}
Run Code Online (Sandbox Code Playgroud)

在第一页中插入Service和NavController并将其用作;

  gotoFinalView(destn) {
    this.masterDetailService.setDestn(destn);
    this.navCtrl.navigateForward("destn-page");
  }
Run Code Online (Sandbox Code Playgroud)

在最后一页提取数据,方法是:

constructor(
    private masterDetailService: MasterDetailService
  ) {
    this.destination = this.masterDetailService.getDestn();
  }
Run Code Online (Sandbox Code Playgroud)


小智 5

这是在您的应用程序中解决用户 Angular Routers 概念问题的有效方法。只需像下面这样声明你的路由器

您的应用路由模块如下所示

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {ViewComponent} from "./crud/view/view.component";
import {CreateComponent} from "./crud/create/create.component";  
import {UpdateComponent} from "./crud/update/update.component";
import {ReadComponent} from "./crud/read/read.component";

const routes: Routes = [
{path: '', component: ViewComponent},
{path: 'create', component: CreateComponent},
{path: 'update/:id', component: UpdateComponent},
{path: 'view/:id', component: ReadComponent}
];

@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Run Code Online (Sandbox Code Playgroud)

:id 是我想发送到该页面的参数。

 this.router.navigate([link + '/' + id]);
Run Code Online (Sandbox Code Playgroud)

在您的第一页中像这样分享您的参数。

在您的第二页中使用 DI(依赖注入)注入激活的路由

constructor(private actRoute: ActivatedRoute)
Run Code Online (Sandbox Code Playgroud)

然后使用以下代码获取参数

this.productID = this.actRoute.snapshot.params['id'];
Run Code Online (Sandbox Code Playgroud)

这是简单的方法。您可以一次发送多个参数。

{path: 'update/:id/:name/:price', component: UpdateComponent}
Run Code Online (Sandbox Code Playgroud)

并获得如下参数

this.productID = this.actRoute.snapshot.params['id'];
this.productName = this.actRoute.snapshot.params['name'];
this.productPrice = this.actRoute.snapshot.params['price'];
Run Code Online (Sandbox Code Playgroud)