你好,我在两个页面之间传递对象。 我在Ionic App中有两个页面。第一页具有Defect对象,并将其发送到第二页。第二页接收该对象并调用其方法。通过使用Ionic核心类NavParams来完成对象的传递。在下面您可以看到对象的接收。缺陷对象。
export class Defect {
public priority: DefectPriority;
public state: DefectState;
public note: string;
public _id: string;
public posX: number;
public posY: number;
public createdAt: number;
public drawingId: string;
public images: DefectImage[];
constructor();
constructor(posY?: number, posX?: number, note?: string, defectId?: string, drawingId?: string) {
if (defectId === undefined || defectId === "") {
throw new Error("incorrect defect id");
}
if (posX === undefined || posY === undefined) {
throw new Error("incorrect coordinates");
}
if (drawingId === undefined || drawingId === "") {
throw new Error("incorrect drawingId");
}
if (drawingId === undefined || drawingId === "") {
throw new Error("incorrect drawingId");
}
this.priority = DefectPriority.NORMAL;
this.createdAt = new Date().getTime();
this.state = DefectState.REPORTED;
this._id = defectId;
this.note = note;
this.posX = posX;
this.posY = posY;
this.drawingId = drawingId;
this.images = [];
}
public getPriority() {
return this.priority;
}
setPriority(value: DefectPriority) {
if (!Object.values(DefectPriority).includes(value.toString())) {
throw new Error("incorrect priority")
}
this.priority = value;
}
public changeState(value: DefectState) {
this.state = value;
}
public setNote(note: string) {
this.note = note;
}
generateImageUrl(creatorName: string): DefectImage {
const newUrl = ObjectId.generate() + '-' + this._id + '.jpg';
const defectImage = new DefectImage(newUrl, creatorName, new Date().getMilliseconds());
this.addImage(defectImage);
return defectImage;
}
addImage(defectImage: DefectImage) {
if (!this.images) {
this.images = [];
}
this.images.push(defectImage);
}
这是接收类:
defect: Defect;
constructor(private viewCtrl: ViewController,
private nav: NavParams,
private navCtrl: NavController,
private photo: PhotoProvider) {
this.defect = this.nav.get('defect');
}
除某些属性外的缺陷类还具有类似以下方法:generateImageUrl
现在,当我将视图更改为内部从参数中获取缺陷的组件时,它只是一个JS对象,而没有有关Defect类方法的信息:这意味着我之后无法调用在缺陷类中定义的方法我将其发送到另一个页面。
请注意,没有自定义方法,例如generateImageUrl
。有没有办法我不会丢失有关该对象的信息?还是我应该根据新组件中的数据重新创建该对象?我的目标在下面的屏幕上显示:
我传递数据的方式:
const defectModal = this.modalCtrl.create(DefectDetailModal, {
defect: this.defect
});
答案 0 :(得分:1)
我假设Defect
是您的应用程序中的实体。 Angular's Style Guide建议对数据模型使用interface
而不是class
。
考虑将接口用于数据模型。
话虽如此,您应该已经创建了一个DefectService,在其中应为要处理的当前缺陷设置一些属性。
然后,您可能已将服务注入到要在其之间共享数据的组件中。然后可以从一个组件设置缺陷,然后使用set
ters和get
ters来在另一个组件中获取缺陷。