2

I'm trying to separate the http request from my component and putting it in a service, how can I pass the response I get from the request to my action in my component?

Like in angular 1 you can do something like the code below in the controller, and do the http request in a service.

var getGenreList = function() {
            coreGenreService.getGenreList(vm.id)
                .then(function(response) {
                     console.log(vm.name);
                });
        }

I tried sort of applying the same logic however I'm not sure how I can pass the response to my controller.

Service:

getUser(){
        this.http.get('http://../api/User?email='+this.customerEmail)
            .map(response => response.text())
            .subscribe(data => {
                if (data) {
                    var userObj = JSON.parse(data);
                    this.UserEmail = userObj.EmailAddress;
                }
        });
    }

I can see that this is getting the json objs but when I do a search I don't see any values in the object, I'm guessing because its not being passed in the searchUser()

searchUser() {
    this.isLoading = true;
    if(!this._searchService.getUser()){ 
        setTimeout(() => {
            this.isLoading = false;
        }, 500)
    }
}

Html input structure:

<input type="text" name="UserEmail" [(ngModel)]="customerEmail" placeholder="Search customer email"> <br>
<button (click)="UserCustomer()" class="omni-btn search-btn float-shadow">Search</button>

1 Answer 1

2

You need to refactor your service this way:

getUser(customerEmail: string): Observable<string>{
    return this.http.get(`http://../api/User?email=${customerEmail}`)
        .map(response => response.json());
}

In your component, you can call the service like this:

searchUser() {
  this.isLoading = true;
  this._searchService.getUser(this.customerEmail)
    .subscribe(user => { 
      this.isLoading = false;

      // To use for data binding in the component
      this.user = user;

      console.log('user = ', user);
  });
}
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks for the response, the .subscribe is saying does not exist on type 'void'
@nCore Define the return type explicitly getUser(): Observable<string>{...}
@AndriyTolstoy where do I inject that? its saying IObservable cannot find name.
@ThierryTemplier where can I console.log the response for now? I wanna see if its returning the right objs.
@nCore you can use console.log but within the map or subscribe callback... I updated my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.