每当我尝试创建新票证时,都会出现以下错误消息:
无法读取未定义的属性“ 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
){}}
new-thread.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
){}}
答案 0 :(得分:0)
threads
变量已声明但从未初始化。应该用一些数据初始化它。例如。
threads: Threads = new Threads(
'0',
'',
'',
new Date((new Date()).getTime() + 24*60*60*1000),
'',
null,
null
);
工作示例:Stackblitz