我试图将JSON从我的api服务传递给任何组件,而无需自行订阅该组件。
在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
}
}
答案 0 :(得分:0)
您犯了两个错误:
您正在返回订阅。
您正在尝试同步访问数据,但是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);
}