我是新来的角7,我想从火力当前认证的用户并映射到我自己的User
模型(无构造函数User
)。
在火力API:
interface UserInfo {
displayName: string | null;
email: string | null;
phoneNumber: string | null;
photoURL: string | null;
providerId: string;
uid: string;
}
在我自己的模型:
export class User{
name: string;
email: string;
contactNo: string;
}
我UserService
@Injectable()
export class UserService {
constructor(
private fireAuth: AngularFireAuth,
) {}
getAuthUser(): Observable<User> {
// this part is not working, how to map to User without changing User constructor?
return this.fireAuth.authState.map(authData => new User({name: authData.displayName}));
}
}
考虑使用一个接口的数据模型。
话虽这么说,你可以,如果你愿意遵循的风格指南做到这一点:
创建可选字段User
interface
:
export interface User{
name?: string;
email?: string;
contactNo?: string;
}
而在你的服务,你可以简单地这样做:
@Injectable()
export class UserService {
constructor(
private fireAuth: AngularFireAuth,
) {}
getAuthUser(): Observable<User> {
return this.fireAuth.authState.map(authData => ({
name: authData.displayName
}));
}
}
这个问题被编辑后
笔者还是建议“提出的问题被编辑”的答案,而是要回答这个问题:
new User({name: authData.displayName})
不能没有调整的构造工作。一个类有一个默认的构造函数,User()
你的情况,不接受任何参数。如果您拥有或希望使用一个类,而不是一个接口(下图所示),再有,你应该能够做一些变通。
粗糙的例子:
// object "as"
authData => <User>{name: authData.displayName, ... other props}
// object "as" 2
authData => {name: authData.displayName, ... other props} as User
// new user, return after changing props
authData => {
const user = new User();
user.name = authData.displayName;
// ...the rest
return user;
}
// "builder" method (basically a constructor)
function buildUser(name: string, ...other props) {
const user = new User();
user.name = authData.displayName;
// ...the rest
return user;
}
眼前的问题是编辑如果你不想使用构造函数和类只是一个没有额外的方法模型,我建议使用的接口。
// interface
export interface User {
name: string;
email: string;
contactNo: string;
}
// inside map
authData => {name: authData.displayName, ...<other props>}
// inside map with type checking 1
authData => <User>{name: authData.displayName, ...<other props>}
This answer有更多的细节。