【发布时间】:2020-03-10 23:04:13
【问题描述】:
每当我尝试创建新票证时,都会收到以下错误消息:
无法读取未定义的属性“id”
这是我的 thread.service.ts,其中有用于创建票证的 AddTicket 方法:
addTicket(
id: string,
heading: string,
user: string,
date: Date,
description: string,
likeCount: number,
timeLeft: number){
const newTicket = new Threads
(
id,
heading,
user,
new Date(date),
description,
likeCount,
timeLeft
);
let generatedId: string;
return this.http
.post<{ name: string }>(
'https://ionic-angular-a0570.firebaseio.com/all-tickets.json',
{
...newTicket,
id: Math.random().toString()
}
)
.pipe(
switchMap(resData => {
generatedId = resData.name;
return this.tickets;
}),
take(1),
tap(tickets => {
newTicket.id = generatedId;
this._tickets.next(tickets.concat(newTicket));
})
);
}
我正在调用 new-thread.page.ts 中的方法:
onCreateTicket(){
this.threadService.addTicket(this.threads.id, this.heading, this.registerService.user, this.threadService.getDate(), this.description, +this.threadService.getLikes(), +12).subscribe();
如果有帮助,这是我的threads.model.ts:
export class Threads {
constructor(
public id: string,
public heading: string,
public user: string,
public date: Date,
public description: string,
public likeCount: number,
public timeLeft: number
){}}
新线程.page.ts:
import { Component, OnInit } from '@angular/core';
import { ThreadsService } from '../main/departmentforum/threads/threads.service';
import { NavController } from '@ionic/angular';
import { RegisterService } from '../register/register.service';
import { Threads } from '../main/departmentforum/threads/threads.model';
@Component({
selector: 'app-new-thread',
templateUrl: './new-thread.page.html',
styleUrls: ['./new-thread.page.scss'],
})
export class NewThreadPage implements OnInit {
heading: string;
description: string;
businessforum: string;
departmentforum: string;
threads: Threads;
constructor(private navController: NavController, private threadService: ThreadsService, public registerService: RegisterService) {}
ngOnInit() {
}
onCreateTicket(){
this.threadService.addTicket(this.threads.id, this.heading, this.registerService.user, this.threadService.getDate(), this.description, +this.threadService.getLikes(), +12).subscribe();
this.navController.navigateBack('main/departmentforum/threads');
}
}
thread.model.ts:
export class Threads {
constructor(
public id: string,
public heading: string,
public user: string,
public date: Date,
public description: string,
public likeCount: number,
public timeLeft: number
){}}
【问题讨论】:
-
请问是哪一行报错了?
-
@MichaelD NewThreadPage.html:48 错误类型错误:无法在 Object.eval [as handleEvent] 处读取 NewThreadPage.onCreateTicket (new-thread.page.ts:26) 处未定义的属性“id”( NewThreadPage.html:48)
-
看起来
this.threads中的onCreateTicket()方法还没有初始化。你确定它是在调用之前定义的吗? -
@MichaelD 我认为 this.threads 来自模型并且只是一个模板。所以我想我还没有初始化它。我如何或在哪里可以这样做?
-
如果不看一下 new-thread.page.ts 或它的模板,我不确定。
标签: javascript angular ionic-framework firebase-realtime-database