将JSON从角度服务返回到组件[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我正在尝试将我的api服务中的JSON传递给任何组件,而无需在组件中订阅它。我在api.service.ts函数中没有任何问题地获取.subscribe内部的数据会发生什么呢?当我试图在其外部获取数据时返回其他内容

这是代码:

api.service.ts


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';

@Injectable({
  providedIn: 'root'
})

export class ApiService {

constructor(private http: HttpClient) {}

public getInfo(URL: string): Observable<any> {
  return this.http.get( URL )
    .pipe(
      tap( (fetchJSON) => JSON.stringify(fetchJSON) )
    )
}

// I'm planning to create more functions like this one to get particular data:

public getParticularData(){
  let infoJSON;
  let URL = "https://jsonplaceholder.typicode.com/posts";
  infoJSON = this.getInfo(URL)
  .subscribe(data =>{ console.log(data) });
  // the console.log(data) inside the .subscribe returns my Json data perfectly

  return infoJSON;
  //this returns: Subscriber {closed: false, _parent: null, _parents: null, _subscriptions: Array(1), syncErrorValue: null, …}

}

}

home.component.ts

*the rest of the imports are here don't worry*
import { ApiService } from '@api/api.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class homeComponent implements OnInit {

constructor( private ApiService: ApiService){

 JSON = this.ApiService.getParticularData();
 console.log(JSON) // returns undefined

}



}
angular api http service
1个回答
0
投票

你犯了两个错误:

  1. 您正在退回订阅。
  2. 您正在尝试同步访问数据,但ajax是异步的。

作为一个简单的解决方案,不要在服务内部订阅,而是在组件中订阅

public getParticularData(){
  let infoJSON;
  let URL = "https://jsonplaceholder.typicode.com/posts";
  infoJSON = this.getInfo(URL)
  .map(data =>{ console.log(data) });
  // the console.log(data) inside the .subscribe returns my Json data perfectly

  return new Promise((resolve)=>{
      infoJSON.subscribe((data)=>resolve(data))
  })

}

零件:

   async myMethod(){
    let data = await this.ApiService.getParticularData();
    console.log(data);
   }
© www.soinside.com 2019 - 2024. All rights reserved.