【发布时间】:2020-03-31 16:56:55
【问题描述】:
我有一个用户配置文件组件正在尝试订阅我的用户服务中的行为主题。我将行为的初始值设置为 null。当用户注册时,我也在我的注册组件中将值传递给我的用户对象,然后将这些相同的值传递给将它们保存在我的下一个主题中的方法。
虽然当我在我的用户配置文件组件中订阅我的 ngOnIt 时,我只能取回我的初始值。我在这里错过了什么吗?根据我的阅读,我已经检查以确保我没有提供我的用户服务的多个实例,并且我使用了 value、getValue 和 subscribe 来获取该值。全部返回 null。
export class UserProfileComponent implements OnInit {
user: User;
ngOnInit() {
// My problem.
this.user = this.userService.getSavedUser().getValue();
console.log(this.user);
}
}
// object
export class User {
firstName: string;
lastName: string;
email: string;
mobile: string;
uid: string;
termsOfAgreement: boolean;
constructor(
email: string,
mobile: string,
firstName: string,
lastName: string,
uid: string,
termsOfAgreement: boolean
) {
this.email = email;
this.mobile = mobile;
this.firstName = firstName;
this.lastName = lastName;
this.uid = uid;
this.termsOfAgreement = false;
}
}
signup.component.ts
onSignup(signupFormData) {
return this.afAuth.auth.createUserWithEmailAndPassword(signupFormData.value.email, signupFormData.value.password)
.then(userInfo => {
// Pass in user info into to user object.
const user: User = new User(signupFormData.value.email,
signupFormData.value.mobile, signupFormData.value.firstName,
signupFormData.value.lastName,
userInfo.user.uid, false);
this.writeNewUser(user);
}).catch((error) => {
this.showError = true;
this.errorMessage = error.message;
})
}
private writeNewUser(user: User): void {
this.userService.addUser(user);
}
// user.service.ts
export class UserService {
private subject: BehaviorSubject<User> = new BehaviorSubject(null);
public addUser(user: User): void {
this.db
.collection("users")
.doc(user.uid)
.set(Object.assign({}, user));
this.saveUser(user);
}
public saveUser(user: User) {
this.subject.next(user);
}
public getSavedUser(): BehaviorSubject<User> {
return this.subject;
}
}
【问题讨论】:
-
嗨@eye4eneye,尝试从您的 sn-ps 中删除冗余代码,例如导入或与您的问题不严格相关的部分代码。找到解决方案会容易得多
-
@MarekSzkudelski 你好,Marek!我删除了一些代码并将我的问题添加到顶部。这有帮助吗?
标签: firebase rxjs observable angular7 behaviorsubject