javascript 如何在Angular的app.service.ts中使用API并在应用程序组件中使用其数据

zqry0prt  于 2023-02-28  发布在  Java
关注(0)|答案(1)|浏览(111)

我正在写一个service.ts,其中使用了API。但是当我想在一个组件中使用它的数据时,它是未定义的。我使用了所有的依赖项

app.component.ts:
constructor(private DATA: DataInfoService){}
this.DATA.ApiService()
this.Informations = this.DATA.Informations;

还有

DataInfoService.ts:

@Injectable({
  providedIn: 'root'
})...
constructor(private http: HttpClient) { }
public ApiService(info: INFO): any {
    var headers = info.headers;
    this.http.post<any>(APIAddress, info.postData, { headers }).subscribe(data => { 
    this.Informations = data
 })
}
vwkv1x7d

vwkv1x7d1#

使用app.service.ts有两种方式
1.用作可观察值
api.service.ts

@Injectable({
  providedIn: 'root'
})...
constructor(private http: HttpClient) { }
public ApiService(info: INFO): any {
    var headers = info.headers;
    return this.http.post<any>(APIAddress, info.postData, { headers })
}

app.component.ts:

constructor(private DATA: DataInfoService){}

ngOnInit(){
  this.DATA.ApiService().subscribe((response) => {
     console.log("Response:", response)
  }, (error) => {})
}

1.作为承诺
api.service.ts

@Injectable({
  providedIn: 'root'
})...
constructor(private http: HttpClient) { }
public ApiService(info: INFO): any {
    var headers = info.headers;
    return new Promise((resolve, reject) => {
       this.http.post<any>(APIAddress, info.postData, { headers 
       }).subscribe((response) => {
          resolve(response)
       }, (error) => {
          reject(error);
       })
    })
}

app.component.ts:

constructor(private DATA: DataInfoService){}

ngOnInit(){
  this.DATA.ApiService().then((response) => {
     console.log("Response:", response)
  }).catch((error) => {})
}

相关问题