我正在尝试使用typescript函数设置图像src属性,但一次又一次地获取“无法设置未定义错误的属性”。我不明白我做错了。
html代码:
<div class="panel-heading" style="border-bottom: 1px solid #cfdbe2; padding: 14px 15px;">
<div class="pull-left">
<img class="media-box-object img-circle thumb32" src="{{other_user_image}}" alt="Image" />
</div>
<div class="panel-title">User</div>
</div>
component.ts代码:
export class ChatComponent implements OnInit {
other_user_image: string;
constructor(
public authService: AuthService,
afAuth: AngularFireAuth,
public db: AngularFirestore,
private router: Router) {}
ngOnInit() {
}
openChatWindow(event: any){
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
var value = idAttr.nodeValue;
// var elem_id = (this.elem);
console.log(value);
var user_chat_room = this.db.collection("users").doc(value)
console.log(user_chat_room);
user_chat_room.ref.get().then(function(documentSnapshot) {
console.log(documentSnapshot.data());
if (documentSnapshot.exists) {
console.log('doneeeeeeee');
console.log(documentSnapshot.data()['profileImageUrl']);
this.other_user_image = documentSnapshot.data()['profileImageUrl'];
console.log(this.other_user_image);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
});
}
}
在打印documentSnapshot.data()['profileImageUrl']
时,我收到了一个类似http://qualiscare.com/wp-content/uploads/2017/08/default-user.png
的字符串,但我无法将其分配给图片src
属性。
答案 0 :(得分:4)
您的问题是在this
定义的函数中使用function () {...}
。在该函数内部,this
为undefined
,因此出错。
更改代码以使用箭头功能,该功能不会创建新的上下文,因此this
保持其含义(对组件的引用):
ngOnInit() { }
openChatWindow(event: any){
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
var value = idAttr.nodeValue;
// var elem_id = (this.elem);
console.log(value);
var user_chat_room = this.db.collection("users").doc(value)
console.log(user_chat_room);
user_chat_room.ref.
get().then(documentSnapshot => {
console.log(documentSnapshot.data());
if (documentSnapshot.exists) {
console.log('doneeeeeeee');
console.log(documentSnapshot.data()['profileImageUrl']);
this.other_user_image = documentSnapshot.data()['profileImageUrl'];
console.log(this.other_user_image);
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
});
}
检查get().then(...)
行。