在订阅方法中更改组件的属性

时间:2017-10-17 08:17:52

标签: angular angular2-template angular2-forms angular2-services

我正在使用angular4来开发我的前端部分。我有一个服务,它返回一个我想要在我的组件中取消订阅的observable。那么如何在subscribe方法中加载数据后更改组件的属性并且即使在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;
            });

        }

1 个答案:

答案 0 :(得分:0)

我认为您正在使用ngAfterViewInit()进行另一次订阅以更新用户变量吗?

当您在构造函数上注入服务实例时,您可以直接访问&#39; this.users&#39;模板和组件中服务的变量。例如:

在您的服务上,只需使用getUserList方法将响应保存在users变量上,如您所见,没有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()

您还可以访问模板上的userListService.users,但如果您进行AOT编译,则会出现一些错误,因为userListService是一个私有变量。

如果你需要向你的后端发出另一个GET请求,只需在你的组件上调用这样的函数:

 refreshUsers () { 
    this.userListService.get().subscribe()
}

此方法将刷新服务的用户变量(您将看到模板上的值可能会发生变化,因为它是一个Observable)