Ionic3+Angular4中Popover回传数据时ViewController注入报错
解决Ionic 3 Popover回传数据时的ViewController注入错误
首先,你遇到的Can't resolve all parameters for ViewController: (?, ?, ?)错误,核心原因是你在AppModule的providers里手动注册了ViewController——Ionic的ViewController是框架负责自动注入的服务,不需要手动添加到providers中,手动注册会破坏它的依赖注入链,导致参数无法解析。
步骤1:移除AppModule中多余的ViewController注册
打开你的AppModule,找到providers数组,删除其中的ViewController项:
// AppModule.ts 修正后的providers部分 providers: [ StatusBar, SplashScreen, DynamicComponentService, PageContainerComponent, HttpService, CommunicationService, { provide: ErrorHandler, useClass: IonicErrorHandler } // 移除这里的ViewController! ]
步骤2:修正Popover组件的关闭方法
你在AutoRefreshComp里的onDismiss方法用错了API:onDidDismiss是给创建Popover的组件用来订阅关闭事件的,Popover内部要关闭并回传数据,应该用this.viewController.dismiss(data):
// AutoRefreshComp.ts 修正后的onDismiss方法 onDismiss(data){ console.log(data); this.viewController.dismiss(data); // 替换onDidDismiss为dismiss }
完整修正后的AutoRefreshComp代码
import { Component, OnInit } from '@angular/core'; import { NavController, NavParams, ViewController } from 'ionic-angular'; @Component({ selector: 'autorefresh-comp', template: ` <ion-grid class="dropdown-setting"> <ion-row> <ion-col col-md-6> <ion-label class="label-text">Auto Refresh</ion-label> </ion-col> <ion-col col-md-4> <ion-toggle checked={{toggleVal}} [(ngModel)]="refreshalVal.toggleValSelected"></ion-toggle> </ion-col> </ion-row> <ion-row> <ion-col col-md-12><hr></ion-col> </ion-row> <ion-row> <ion-col col-md-4> <ion-label class="label-text">Set Time</ion-label> </ion-col> <ion-col col-md-8> <ion-list > <ion-item> <ion-label>Select</ion-label> <ion-select [(ngModel)]="refreshalVal.seconds" (ionChange)="onDismiss(refreshalVal)" interface="popover"> <ion-option value="{{enumVal[i]}}" *ngFor="let sec of enumVal; let i = index;" >{{enumVal[i]}} seconds</ion-option> </ion-select> </ion-item> </ion-list> </ion-col> </ion-row> <h1>{{refreshalVal.toggleValSelected}}</h1> <h1>{{refreshalVal.seconds}}</h1> <ion-grid> ` }) export class AutoRefreshComp { enumVal: any; toggleVal: any; refreshalVal:any={}; constructor(public navCtrl: NavController, public navParams: NavParams,public viewController:ViewController) { } ionViewWillLoad() { this.enumVal = this.navParams.get("enumVal"); console.log("enumVal received:: ", this.enumVal); this.toggleVal = this.navParams.get("toggleVal"); this.refreshalVal.toggleValSelected= this.toggleVal; console.log("toggleVal received:: ", this.toggleVal); } ionViewDidLoad() { console.log('ionViewDidLoad PopoverPage'); } onDismiss(data){ console.log("准备回传的数据:", data); this.viewController.dismiss(data); } }
另外,我把(click)事件改成了(ionChange),这样当用户选择下拉选项时才触发关闭,更符合交互逻辑——原来的(click)会在用户点击下拉框时就关闭Popover,这显然不是你想要的效果。
做完这两步后,你的Popover应该就能正常关闭并回传数据了,ViewController的注入错误也会消失。
内容的提问来源于stack exchange,提问作者Md Noorshid_ReactiveWorks
相关产品推荐
相关产品推荐

