How to assign local variable from observable Angular2

MostafaItani

What is the proper method to assign a local object from an http response observable?

I want to assign myUser object to the response that I get from http, which is of the same type. Here is my code:

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.
}
    }

Logging this.myUser within the observable nets a positive result, however when I try to access the local variable from a child component that is provided by this service, it returns undefined, such as this.formService.logUser(); if used in a child component, returns undefined.

What is the proper method to broadcast an object from a service to a child component? I may be having async issues as the child component is being initialized before the service even gets the object from the http.

UPDATED QUESTION: Child Component

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..
  }
}

So my end game is only to get the service to broadcast myUser for the child component to receive it and then display its data members to a form. But any time I assigned myUser to localUser it appears as undefined.

Boris Lobanov

You can try to use a BehaviorSubject to store the user object:

In your service:

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());
}

In your component:

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
        });  
    }
}

Also, very important: you want the components to use the same instance of the service, so remove it from the providers from both components and add it to the providers of some higher level component, so that they share one instance.

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

Assign array value to local variable

分類Dev

How to assign JSON (in a subscribe) to a variable in angular

分類Dev

How can I assign a value from the Angular Material autocomplete to a variable in my component?

分類Dev

how to extract text from a html element by id and assign to a php variable?

分類Dev

How to assign something to global variable from within FOR loop in batch

分類Dev

How to unsubscribe from observable created by an Angular Service

分類Dev

How to access local variable of method in angular 2 unit test

分類Dev

Angular2 ChangeDetection or Observable?

分類Dev

Variable from API not getting passed into local storage in Angular

分類Dev

Angular2: How to subscribe to Http.post observable inside a service and a component properly?

分類Dev

How to expose afterClosed() method / observable from Modal Wrapper Service in Angular

分類Dev

javascript: modify global variable from local variable

分類Dev

Separate and assign objects to variable from an array

分類Dev

assign last positional parameter to variable and remove it from "$@"

分類Dev

How to get component properties from main component in Angular2?

分類Dev

Angular 2 - Sort list from Observable

分類Dev

How can I create array elements dynamically and assign values (from variable with the same names) to the elements

分類Dev

How to dynamically create a local variable?

分類Dev

Angular2コンテキストでのObservableの「from」メソッド

分類Dev

How to assign a variable the output of a shell command in Tupfile?

分類Dev

How to assign istringstream and ifstream to an istream variable?

分類Dev

Python/BeautifulSoup - how to assign html code to variable

分類Dev

How to assign more ranges to same variable?

分類Dev

how to assign values to list type class variable?

分類Dev

How to pass assign variable value in FreeMarker function

分類Dev

How to assign an array to a variable of a sql query

分類Dev

How to assign variable if Cursor returns Bit of 0

分類Dev

Angular: normal array from observable

分類Dev

How to modify data in Observable in Angular 2?

Related 関連記事

  1. 1

    Assign array value to local variable

  2. 2

    How to assign JSON (in a subscribe) to a variable in angular

  3. 3

    How can I assign a value from the Angular Material autocomplete to a variable in my component?

  4. 4

    how to extract text from a html element by id and assign to a php variable?

  5. 5

    How to assign something to global variable from within FOR loop in batch

  6. 6

    How to unsubscribe from observable created by an Angular Service

  7. 7

    How to access local variable of method in angular 2 unit test

  8. 8

    Angular2 ChangeDetection or Observable?

  9. 9

    Variable from API not getting passed into local storage in Angular

  10. 10

    Angular2: How to subscribe to Http.post observable inside a service and a component properly?

  11. 11

    How to expose afterClosed() method / observable from Modal Wrapper Service in Angular

  12. 12

    javascript: modify global variable from local variable

  13. 13

    Separate and assign objects to variable from an array

  14. 14

    assign last positional parameter to variable and remove it from "$@"

  15. 15

    How to get component properties from main component in Angular2?

  16. 16

    Angular 2 - Sort list from Observable

  17. 17

    How can I create array elements dynamically and assign values (from variable with the same names) to the elements

  18. 18

    How to dynamically create a local variable?

  19. 19

    Angular2コンテキストでのObservableの「from」メソッド

  20. 20

    How to assign a variable the output of a shell command in Tupfile?

  21. 21

    How to assign istringstream and ifstream to an istream variable?

  22. 22

    Python/BeautifulSoup - how to assign html code to variable

  23. 23

    How to assign more ranges to same variable?

  24. 24

    how to assign values to list type class variable?

  25. 25

    How to pass assign variable value in FreeMarker function

  26. 26

    How to assign an array to a variable of a sql query

  27. 27

    How to assign variable if Cursor returns Bit of 0

  28. 28

    Angular: normal array from observable

  29. 29

    How to modify data in Observable in Angular 2?

ホットタグ

アーカイブ