尝试从服务中获取数据到 component.ts

Trying to get data from service into component.ts

我正在尝试从服务中获取数据并将其放入我的 component.ts 文件中。我有订阅 http get 的服务,它 returns 数据但是在我尝试获取组件中的数据之后。我只是不知道如何去做,直到它完成服务中的调用才尝试获取数据。

我不确定我是不是管错了,还是应该订阅。我查过的任何东西都没有真正的帮助。

在控制台中我收到管道错误,然后在错误发生后它从服务输出可观察值。

我的SearchService.ts

import { Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Row } from "../../app/row";
import { Observable } from "rxjs";
import { of } from "rxjs";

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

  players: Observable<Row[]>;

  constructor(private http: HttpClient) { }

  getPlayers(searchTerm: String): Observable<Row[]>{
    let ROOT_URL =
    "http://lookup-service-prod.mlb.com/json/named.search_player_all.bam?sport_code='mlb'&active_sw='Y'&name_part='" +
   searchTerm +
    "%25'";
    this.http.get<Row[]>(ROOT_URL).subscribe(data => {
      let res = data["search_player_all"];
      let query = res["queryResults"];
      let row = query["row"];
      if (row != null) {
        this.players = row;
        console.log(this.players);
        return this.players;
      }
    });
    return this.players;
  }
}

AppComponent.ts

import { Component } from "@angular/core";
import { Row } from "../app/row";
import { Observable } from "rxjs";
import { map } from 'rxjs/operators';
import { SearchServiceService } from "../app/services/search-service.service"

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.scss"]
})
export class AppComponent {
  players: Row[];
  value = "";
  buttonClicked = false;
  numReturned = -1;
  searchTerm = "";
  constructor(private searchService: SearchServiceService) {}

  getData() {
    if (this.value != "") {
      this.searchTerm = this.value;

      this.searchService.getPlayers(this.searchTerm).pipe(map(data => {
        if(data == null) {
          console.log('IS NULL');
        }
        else {
          console.log('in service');
          this.players = data;
          console.log(this.players);
          this.buttonClicked = true;
        }
      }));

      if(this.players == null) {
        console.log('null');
        this.numReturned = -1;
      }

    }
  }

尝试 return 就像这样 http.get:

getPlayers(searchTerm: String): Observable<Row[]>{
    return this.http.get<Row[]>(ROOT_URL);
}

此外,在您的代码中,this.players 不是 Observable,它是您 api returned.

的纯数据

所以不是这个:

this.searchService.getPlayers(this.searchTerm).pipe(map(

只需订阅:

this.searchService.getPlayers(this.searchTerm).subscribe((data: any) => { <process your data here> });