【发布时间】:2017-09-24 02:13:12
【问题描述】:
我正在开发一个聊天应用程序。有一个 chat.component.ts 连接到服务并获取“消息”和“显示名称”。
在 chat.component.html 中绑定 displayName 如下:
<p>You are logged in as: {{displayName}}</p>
这就是 chat.component.ts 的样子:
import { Component, OnInit, AfterViewChecked, ViewChild, ElementRef } from '@angular/core';
import { AfService } from '../af.service';
import { FirebaseListObservable } from 'angularfire2/database';
@Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.css']
})
export class ChatComponent implements OnInit {
public newMessage: string;
public messages: FirebaseListObservable<any>;
public displayName: string;
constructor(public AF: AfService) {
this.messages = this.AF.messages;
this.displayName = this.AF.displayName;
}
ngOnInit() {}
@ViewChild('scrollMe') private myScrollContainer: ElementRef;
ngAfterViewChecked() {
this.scrollToBottom();
}
scrollToBottom(): void {
try {
this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
} catch(err) { console.log('Scroll to bottom failed yo!')}
}
isMe(email) {
if(email == this.AF.email)
return true;
else
return false;
}
sendMessage(){
this.AF.sendMessage(this.newMessage);
this.newMessage = '';
}
}
AfService 中的 displayName 属性是从以前的组件中设置的。
这就是问题所在:
当我从头开始处理应用程序并登录时,displayName 可用。但是,当我刷新 chat.component.html 页面时, displayName 变得未定义。例如,如果我执行 console.log(this.AF.displayName),它会按原样显示,但是,如果我执行 console.log(this.displayName),它是未定义的。
有趣的是,'messaages' 一直在正常工作。
我认为这更像是一个概念性问题,我正在努力弄清楚为什么会发生这种情况以及如何解决它。这个问题我也找不到更好的标题了。
更新,这是 AfService:
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { AngularFireAuth } from 'angularfire2/auth';
import { FirebaseListObservable } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
import * as firebase from 'firebase/app';
@Injectable()
export class AfService {
user: Observable<firebase.User>;
messages: FirebaseListObservable<any>;
displayName: string;
email: string;
constructor(public db: AngularFireDatabase, public afAuth: AngularFireAuth) {
this.messages = this.db.list('messages');
}
loginWithGoogle(){
return this.afAuth.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
};
logout(){
this.afAuth.auth.signOut();
};
sendMessage(text) {
var message = {
message: text,
displayName: this.displayName,
email: tis.email,
timestamp: Date.now()
};
this.messages.push(message);
};
getDisplayName() {
return this.displayName;
}
}
【问题讨论】:
-
您的组件没有显示在任何地方分配的
this.displayName值。所以console.log(this.AF.displayName)在console.log(this.displayName)返回undefined时正确显示是有意义的。 -
很抱歉,我发布了一个经过编辑的代码版本。我会编辑以避免混淆。
-
感谢更新。如果问题仍然存在,您能否也发布您的 AFService?
-
好的,我已经更新了。我没有搞砸的服务我尝试添加一个 getDisplayName() 函数,但没有奏效。
标签: javascript angular firebase