有一条路线负责在页面上显示用户信息。该路由具有:id参数,与用户的ID属性相对应。
const appRoutes: Routes = [
{ path: 'user/:id', component: UserDetailComponent }
];
export class User {
id: number;
name: string;
age: number;
photoUrl: string;
info: string;
constructor(name: string, age: number, photoUrl: string, info: string, id: number) {
this.name = name;
this.age = age;
this.photoUrl = photoUrl;
this.info = info;
this.id = id;
}
}
我需要检索特定的AngularFirestoreDocument,该文件包含具有路由器参数中指定的id属性/字段的用户。
如何在服务中创建getUser(id:number)方法,然后在UserDetailComponent中使用它来显示路由器参数指定的用户?
P.s。作为用户ID,我不会使用FirestoreDocument标识符,我想要自己的自定义ID值。
export class UsersService {
usersCollection: AngularFirestoreCollection<User>;
users: Observable<any[]>;
constructor(private firebase: AngularFirestore) {
this.users = firebase.collection('users').valueChanges();
}
getUser(id: number) {
// How to get user with particular field(property)?
//For example I want to retrieve from my Cloud Firestore user with id == 1 and return it.
}
export class UserDetailComponent implements OnInit {
user: User;
userId: number;
constructor(private usersService: UsersService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.params
.subscribe((params) => {
this.userId = +params['id'];
this.user = this.usersService.getUser(this.userId);
});
});
}