1

I've created this HttpService which leverages the HttpClient. In the service i have 1 method called getUserId() that is making a http request to a mock api. In the response I wan't to grab the userId property and have the getUserId() return the userId.

The idea is to be able to get the userId in a component by creating an instance of the HttpService and call getUserId() method. I don't know if this is the right approach but the purpose of the httpservice is to handle all http requests and by creating an instance of it in a component i can access all it's functions depending on what data i need. I am completely new at Angular.

How do i make it so that getUserId() returns the userId property of the http response?

httpService:

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';

interface IuserData{
  userId: number;
}

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(private http: HttpClient) { }

  getUserId(){  
    return this.http.get<IuserData>("https://jsonplaceholder.typicode.com/todos/1").subscribe(data => {
      console.log('User ID: ' + data.userId)
    })
  }
}
2
  • what is your issue ? Commented Oct 24, 2018 at 8:05
  • My issue is that i need getUserId() to return data.userId. Commented Oct 24, 2018 at 8:08

3 Answers 3

1

You shouldn't have subscribed to this.http.get in your service. Instead you should have done that in your Component.

Also, instead of passing the whole TODO object, you'll have to map it to just return an object with a userId key in it so that it serves your purpose of the supplying the Type T to the get method of HttpClient.

import { Injectable } from '@angular/core';
import { HttpClient} from '@angular/common/http';
import { map } from 'rxjs/operators';

interface UserId {
  userId: number;
}

@Injectable({
  providedIn: 'root'
})
export class HttpService {

  constructor(private http: HttpClient) { }

  getUserId(){  
    return this.http.get<UserId>("https://jsonplaceholder.typicode.com/todos/1")
      .pipe(
        map(todo => ({ userId: todo.userId }))
      );
  }
}

Now in your Component:

constructor(private http: HttpService) { }
...
ngOnInit() {
  this.http.getUserId()
    .subscribe(userId => console.log(userId));
}

Side Note: Angular and TypeScript Styleguide doesn't really recommend prefixing I before interface names. So I've fixed the name for you.

Sign up to request clarification or add additional context in comments.

1 Comment

I see, thanks for an informative answer. I'm used to .NET, my bad about the interface prefix. Is there a way to access userId outside the Observable. I mean can i assign the userId to a variable?
1

Just inject your service in the component constructor (privately) and call your method then wherever you want:

constructor(private httpService HttpService) {
    this.httpService.getUserId();
  }
  • Here your method will be called within the constructor, else you can call it in a different method if you want since your service is well injected in the component's constructor.
  • Do not forget to import the service in the component's file

  • It is better to subscribe in the component's side not in the service's one

  • The component and the service should be visible to each other by default (within the same NgModule parameters for exemple)

Comments

0

You need to change your service just to return the observable and subscribe in your component as follows,

Service

 getUserId(){  
    return this.http.get<IuserData>("https://jsonplaceholder.typicode.com/todos/1");
  }

and in component,

 this.http.getUserId().subscribe(userId => console.log(userId));

Comments

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.