我试图在这样的反应对象上设置一个参数id:
reaction: { message_id: ""};
async activate(params) {
alert(params.id);
this.reaction.message_id = params.id;
}
警报正确,因此提示正确。但后来我在控制台收到了:
ERROR [app-router] TypeError: Cannot set property 'message_id' of undefined
编辑:
import { HttpClient, json } from "aurelia-fetch-client"
import { autoinject } from "aurelia-framework"
import { Router } from 'aurelia-router'
@autoinject
export class message {
message: { reactions: Reaction[], id: "" };
editing: boolean;
reaction: Reaction;
constructor(private http: HttpClient, private router: Router) {
this.editing = false;
}
created() {
this.getMessage();
}
async activate(params) {
alert(params.id);
this.reaction.message_id = params.id;
}
getMessage() {
this.http.fetch('message/show', {
body: json(this.router.currentInstruction.params.id)
})
.then(response => response.json())
.then(data => {
this.message = data;
});
}
update() {
this.http.fetch('message/update', {
body: json(this.message)
})
.then(response => {
if (response.status == 200) {
swal({
title: "Bericht succesvol geupdatet",
type: "success",
showConfirmButton: false,
timer: 2000
});
}
this.editing = false;
});
}
destroy() {
swal({
title: 'Weet u het zeker?',
type: 'warning',
showCancelButton: true,
confirmButtonText: 'Ja verwijder dit bericht',
cancelButtonText: 'Stop!',
confirmButtonColor: '#002e5b',
}, (isOk) => {
if (isOk) {
this.http.fetch('message/destroy', {
body: json(this.message)
}).then(data => {
swal({
title: 'Verwijderd',
text: 'Het bericht is succesvol verwijderd',
type: 'success',
showConfirmButton: false,
timer: 3000
});
});
this.router.navigate("/dashboard");
}
});
}
post() {
this.message.reactions.push(this.reaction);
this.http.fetch('reaction/store', {
body: json(this.reaction)
}).then(response => {
if (response.status == 200) {
swal({
title: "Reactie succesvol aangemaakt",
type: "success",
showConfirmButton: false,
timer: 2000
});
this.reaction = {};
}
});
}
}
export class Reaction {
message_id: number;
account_id: number;
reaction: string;
}
答案 0 :(得分:1)
您只提供reaction
的类型,而不是值。您必须在使用它之前将其实例化。试试这个:
reaction: Reaction; //this has a type but it is undefined
reaction = new Reaction(); //this has a type and it is instantiated! use this line!
这是一个简单的Typescript问题,与Aurelia无关。