A
A
ajky2016-12-14 20:20:41
JavaScript
ajky, 2016-12-14 20:20:41

How to get subscribe() value in service from component?

If without a request to the server, then it's easy, but the result of the request cannot be transmitted :/
You need to translate the value into the component.

@Injectable() 
export class UserService {
    constructor(
        private auth:       Auth,
        private http:       Http,
        private authHttp:   AuthHttp) {}
  
    getUsers() {
        this.authHttp
            .get(APP_SERVER + 'api/users')
            .map((response: Response) => response.json())
            .subscribe(
            (data) => {
                return data;
            },
            (error) => {
                console.log('user service error');
            }
        );
    }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
_
_ _, 2016-12-15
@ajky

I don't quite understand what's wrong with you

getUsers() {
  return this.authHttp
    .get(APP_SERVER + 'api/users')
    .map((response: Response) => response.json());
}

constructor(svc: UserService) {
  svc.getUsers().subscribe((response) => console.log(response));
}

D
Dmitry Barakin, 2016-12-14
@xeeqqw

No way. I'll try to explain (don't kick much for terminology).
The bottom line is that in this example you are not returning anything from the getUser() function.
refers not to the getUser() function, but to the lambda

(data) => {
    return data;
}

To get the value in the component, you still have to return a Promise or Observable from the service (as in your case) and subscribe to the result with then (Promise) or subscribe (Observable). Somehow interacting with asynchronous operations (http) will not work

V
Vitaly, 2016-12-14
@vitali1995

There is an option, and it's pretty simple. It is enough to add an EventEmitter to the service, which will send emit (data) as a result of each request. Any component that includes this service, in the constructor, subscribes to the dispatched events, after which it can update the content.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question