在订阅方法中更改组件的属性
我正在使用angular4来开发我的前端部分。我有一个服务,它返回我想要在其中订阅的observable。因此,如何在加载后更改组件的属性订阅方法中的数据,甚至在ngOnInit方法之后仍保留,并且不会返回到默认值。 这是我的组件代码:在订阅方法中更改组件的属性
import {CreateUserComponent} from '../create-user/create-user.component';
import {UpdateUsersCredentialsComponent} from '../update-users-credentials/update-users-credentials.component';
import { Component, OnInit, AfterViewInit } from '@angular/core';
import { MdDialog, MdDialogRef, MdDialogConfig } from '@angular/material';
import{UsersListService} from '../shared/users-list.service'
import { User } from 'app/pages/Users/shared/user';
@Component({
selector: 'vr-users-list',
templateUrl: './users-list.component.html',
styleUrls: ['./users-list.component.scss']
})
export class UsersListComponent implements OnInit,AfterViewInit {
private users:any[]=["1","2","3"];
private selectedUser:User;
constructor(public dialog: MdDialog,private userListService: UsersListService) {
}
public get $selectedUser(): User {
return this.selectedUser;
}
public set $selectedUser(value: User) {
this.selectedUser = value;
}
ngOnInit() {
this.userListService.getUserList().subscribe (
data =>{
console.log("those are data "+data.length);
this.users=data;
});
}
ngAfterViewInit(){
this.userListService.getUserList().subscribe (
data =>{
console.log("those are data "+data.length);
this.users=data;
});
}
openUsersDetails() {
let config = new MdDialogConfig();
let dialogRef:MdDialogRef<UpdateUsersCredentialsComponent> = this.dialog.open(UpdateUsersCredentialsComponent, config);
dialogRef.componentInstance.email =this.selectedUser.$email;
}
openCreateUser() {
this.dialog.open(CreateUserComponent);
}
}
这是getUserList方法
getUserList(){
//this method is returning the items
return this.http.get(this.usersUrl)
.map(res => {
this.users=res['items'];
return this.users;
});
}
我认为你正在使用ngAfterViewInit()再拍认购,以更新的用户变量吗?
当您在构造函数中注入您的服务实例时,您可以直接访问模板和组件中服务的this.users变量。例如:
您的服务,只需使用getUserList方法,以节省用户变量的反应,当你看到没有return语句:
getUserList(){
//this method is returning the items
return this.http.get(this.usersUrl)
.map(res => {
this.users=res['items'];
});
}
在组件,你可以做一个函数:
getUsersFromService() {
return this.userListService.users
}
然后,当你需要访问这个变量,你需要调用getUsersFromService()
您也可以访问在T userListService.users模板,但如果你做AOT编译,你会得到一些错误,因为userListService是一个私有变量。
如果您需要另一个GET请求,后端只需拨打您的组件上这样的功能:
refreshUsers() {
this.userListService.get().subscribe()
}
此方法将刷新该服务的用户变量(你会看到该值可能会改变在你的模板上,因为它是一个Observable)
同样的问题:/ – fbm
'那么,如何在订阅方法中加载数据后更改组件的属性,并保持ngOnInit方法后仍然不返回到默认值'....您应该可以通过更改userListService.users变量来完成此操作!尝试做一个方法(在你的组件上),在其中改变它的值,然后像这样将它放在你的模板上{{userListService.users}} –
如果你展示你如何从你的服务中发布Observable的值,将代码显示在getUserList()方法上会很有用! –
我已经更新了帖子 – fbm