如何从可观察的Angular2中分配局部变量

时间:2018-02-12 14:05:18

标签: angular http

从http响应中观察本地对象的正确方法是什么?

我想将myUser对象分配给我从http获得的响应,该响应属于同一类型。这是我的代码:

import 'rxjs/add/observable/from';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';

import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';

import { UpdateUser } from '../_models/updateuser';


@Injectable()
export class FormService {

    private myUser : UpdateUser;

    constructor(private http: Http) {
    }

    getUser(id: number): Observable<UpdateUser> {
        const _url = 'https://192.168.1.2:4444/api/auth/getuser/' + id;
        const headers = new Headers();
        headers.append('X-User', sessionStorage.getItem('username'));
        headers.append('X-Token', sessionStorage.getItem('token'));
        headers.append('X-AccessTime', sessionStorage.getItem('AccessTime'));
        headers.append('Content-Type', 'application/json');
        const options = new RequestOptions({ headers: headers });

        return this.http.get(_url, options)
            .map(response => {
                const responseAsObject = response.json();
                this.myUser = responseAsObject; //<--- Here
                console.log(this.myUser);
                return responseAsObject;
            });
    }  



     logUser(){
      console.log(this.myUser) //<--- undefined if called formService.logUser() from child components.
}
    }

在observable中记录this.myUser会产生一个肯定的结果,但是当我尝试从这个服务提供的子组件访问本地变量时,它会返回undefined,例如this.formService.logUser();如果在子组件中使用,则返回undefined。

将对象从服务广播到子组件的正确方法是什么?我可能遇到异步问题,因为在服务甚至从http获取对象之前,正在初始化子组件。

更新的问题: 子组件

import { FormService } from '../../../../_services/form.service';
import { UpdateUser } from '../_models/updateuser';

@Component({
  selector: 'update-form',
  templateUrl: './updateForm.html',
  providers: [FormService],
})

export class UpdateFormComponent implements OnInit{


  private localUser : UpdateUser;

  ngOnDestroy() {
  }

  constructor(
    private formService: FormService,
  ) {}

  ngOnInit() {

    this.formService.logUser(); //undefined
    this.formService.myUser = this.localUser; //Assign something like this, but with an observable..
  }
}

所以我的最终游戏只是让服务广播myUser让子组件接收它然后将其数据成员显示到表单。但是,只要我将myUser分配给localUser,它就会显示为未定义。

1 个答案:

答案 0 :(得分:2)

您可以尝试使用BehaviorSubject来存储用户对象:

在您的服务中:

private myUser = new BehaviorSubject<UpdateUser>(null);

getUser() {
    // ...
    return this.http.get(_url, options)
        .map(response => {
            const responseAsObject = response.json();
            this.myUser.next(responseAsObject); // change the value!
            console.log(this.myUser);
            return responseAsObject;
        });
}

logUser() {
    console.log(this.myUser.getValue());
}

在您的组件中:

export class UpdateFormComponent implements OnInit{
  private localUser : UpdateUser;

  constructor(
    private formService: FormService,
  ) {}

    ngOnInit() {
        this.formService.myUser
            .filter(user => user !== null)
            .subscribe(user => {
                this.formService.logUser(); // also 'user' here is the user object from the service, you can do whatever you want with it
        });  
    }
}

此外,非常重要:您希望组件使用相同的服务实例,因此请从两个组件的提供程序中删除它,并将其添加到某些更高级别组件的提供程序中,以便他们共享一个实例。