0

Сервис:

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

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

  private response:any;
  constructor(private http: HttpClient) {
  }

  getResponse(userName) {
    this.http.get('https://api.github.com/users/' + userName)
      .subscribe((response: any) => {
        this.response = response;
        console.log(response.name);
        return this.response;
      });
  }
}

Компонент:

import { Component } from '@angular/core';
import { NewServiceService } from './new-service.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less'],
  providers: [NewServiceService]
})
export class AppComponent {
  private userName:string = "";
  private response:any;

  constructor(private nss:NewServiceService){

  }

  search(){
    this.response = this.nss.getResponse(this.userName);
    console.log(this.response);
  }
}

Результат:

введите сюда описание изображения

введите сюда описание изображения

там где undifined должен выводиться ответ от сервера. Ответ есть (это видно с вывода имени в сервисе), но при передачу в компонент с ним что то происходит. Что я упускаю?

3
  • зачем вы вообще делаете return внутри подписки? это в официальной документации так написано? 3 фев 2019 в 12:24
  • @overthesanity хотел возвратить ответ 4 фев 2019 в 0:15
  • subscribe возвращает Subscription а не ответ 4 фев 2019 в 6:21

1 ответ 1

1

В методе getResponse вашего сервиса, напишите return вот так:

return this.http.get('https://api.github.com/users/' + userName)
  .subscribe((response: any) => {
    this.response = response;
    console.log(response.name);
    return this.response;
  });

Ошибка не связана ни с angular ни с typescript. Это основы работы с функциями и методами. У вас метод сервиса просто ничего не возвращает, отсюда и undefined.

1
  • Спасибо за ответ...сам запутался. Подумал что в сабскрпйб ретурн с функции делает 3 фев 2019 в 3:13

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.