关于 Ionic4 对 NavController 进行跳转传递参数的 解决方案 (NavParams)

首先我们先确认好 传送方,接收方

传送方 demoSend 的 template:

<ion-header>
    <ion-toolbar>
        <ion-title>传送方</ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
    <ion-list>
        <ion-item>
            <ion-input type="text" placeholder="Awesome Input" [(ngModel)]="uName"></ion-input>
        </ion-item>
    </ion-list>
    <ion-button (click)="sendArg()">
        Click me
    </ion-button>
</ion-content>

传送方 demoSend 的 Ts:

import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { Router } from '@angular/router';
@Component({
    selector: 'app-demo-send',
    templateUrl: './demoSend.html',
    styleUrls: ['./demoSend.page.scss'],
})
export class demoSendPage implements OnInit {
    uName: string = "";
    constructor(private nav: NavController, private myRouter: Router) { }

    ngOnInit() {
    }
    // 跳转到 demoArg 并发送参数
    async sendArg() {
        await this.nav.navigateForward(['/demoArg'], {
            queryParams: {
                userName: this.uName
            }
        });
    }
}

接收方 demoArg 的 template:

<ion-header>
    <ion-toolbar>
        <ion-icon style="float:left;width:50px;height:30px;" name="arrow-back" (click)='goBack()'>
        </ion-icon>
        <ion-title>demoArg</ion-title>
    </ion-toolbar>
</ion-header>

<ion-content>
    <h1>{{"接收到的参数为"+uName}}</h1>
</ion-content>

接收方 demoArg 的 Ts:

import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import { ActivatedRoute, Params } from '@angular/router';

@Component({
    selector: 'app-demo-arg',
    templateUrl: './demoArg.page.html',
    styleUrls: ['./demoArg.page.scss'],
})
export class demoArgPage implements OnInit {
    uName: string = "";
    constructor(private nav: NavController, public activeRoute: ActivatedRoute) { }

    ngOnInit() {
        // 需要接收用户传递来的参数,并显示在视图中
        this.activeRoute.queryParams.subscribe((params: Params) => {
            console.log(params);
            this.uName = params.userName;
        })
    }
    // 返回
    goBack() {
        this.nav.back();
    }

}

你可能感兴趣的:(Ionic)