尝试从角度服务中检索Http JSON

时间:2019-03-07 04:30:47

标签: angular typescript

我正在尝试建立一个服务,该服务将执行Http get并将JSON数据返回给调用方。我想我根据下面的示例正确设置了所有内容,但是编译器不允许我调用服务来获取数据。告诉我我正在尝试调用void函数,但是我在那个函数中显式返回了一个值。这是该服务的代码:

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

@Injectable({
  providedIn: 'root'
})
export class AircraftInfoService {
  aircraft: string;
  api = 'https://<notshow>/api/PApps_AircraftInfo?apikey=<notshown>';

  constructor(private httpClient: HttpClient) {   
  }

  ngOnInit() {
    console.log('aircraftInfoservice');
  }

  getAircraft() {
    this.httpClient.get(this.api).subscribe((res)=>{
      console.log('aircraft: ', res );
      return res;
    })
  }
}

这是我试图在app.compontent.ts中调用该服务的地方:

export class AppComponent implements OnInit{
  className: string;
  isAuthenticated$:         Observable<boolean>;
  appSettings: AppSettings;
  appSettingsSub: Subscription;
  themeClass: string;
  _wing: string;
  _theme: string;
  aircraftDB: string;


  constructor(
    private titleService: TitleService,
    public appSettingsService: AppSettingsService,
    private httpClient: HttpClient,
    public aircraftInfoService: AircraftInfoService,
    private matIconRegistry: MatIconRegistry,
    private domSanitizer: DomSanitizer,
    private adalService: AdalService,      
    private logger: LogService,
    private overlayContainer: OverlayContainer,
    @Inject(LOCAL_STORAGE) private storage: WebStorageService
    ){

    adalService.init(environment.config);


    this.matIconRegistry.addSvgIcon(
      "historical-tracking-black-48",
      this.domSanitizer.bypassSecurityTrustResourceUrl("../assets/historical-tracking-black-48.svg")
);
    this.matIconRegistry.addSvgIcon(
      "historical-tracking-black-48-inactive",
      this.domSanitizer.bypassSecurityTrustResourceUrl("../assets/historical-tracking-black-48-inactive.svg")
    );
  } 

  ngOnInit(){
    this.className = this.constructor.toString().match(/\w+/g)[1];

    this.appSettings = this.appSettingsService.behaviorSubject.getValue();
    this.appSettingsSub =     this.appSettingsService.behaviorSubject.asObservable().subscribe(value => {
      this.appSettings = value;
      this._wing = this.appSettings.wing;
      this.themeClass = this.appSettings.theme;
    }); 

    this.aircraftDB = this.aircraftInfoService.getAircraft();

    this.adalService.handleWindowCallback();
    this.logger.debug(this.className, "adal userInfo: ",     this.adalService.userInfo);

  }

this.aircraftDB = this.aircraftInfoService.getAircraft()

引起问题:

  

类型'void'不能分配给类型'string'

我在做什么错了?

谢谢

3 个答案:

答案 0 :(得分:0)

此方法将首先返回Subscription。所以你得到这个错误。您可以通过两种方式解决该问题:

getAircraft() {
    this.httpClient.get(this.api).subscribe((res)=>{
        console.log('aircraft: ', res );
        return res;
    })

aircraftDB的类型更改为any aircraftDB: any。但这不是正确的方法。另一种方法是返回预订,如下所示:

getAircraft() {
    return this.httpClient.get(this.api);
}

在您的 component.ts 中,您可以订阅它并将res分配给this.aircraftDB

this.aircraftInfoService.getAircraft().subscribe((res)=>{
    console.log('aircraft: ', res );
    this.aircraftDB = res;
});

答案 1 :(得分:0)

选项1 更改为您的服务

    getAircraft() {
      this.httpClient.get(this.api).pipe(
        map((res: any) => {
          return res.toString();
        })
      );
   }

选项2

从服务中返回可观察对象,并将其订阅到您的AppComponnet

  getAircraft() {
    return this.httpClient.get(this.api);
  }

和在AppComponent中

this.aircraftInfoService.getAircraft().subscribe((res: any) {
  console.log('Response', res);
});

答案 2 :(得分:0)

why do you want to reference your service ?个问题。如果您只想在组件中调用service,则只需在subscribe中进行操作即可。 因为http的呼叫是async,即you don't get the data right away... you have to make the requst and await the response,所以Observable就是这样。

因此,一个好的解决方案是稍微更改您的服务实现,它应该返回observable<datatype>

getAircraft():Observable<any[]> {
    this.httpClient.get(this.api).subscribe((res)=>{
      console.log('aircraft: ', res );
      return res;
    });
}

然后在您的component中,您只需要subscribe就可以了

ngOnInit() {
  ...
   this.aircraftInfoService.getAircraft().subscribe((data)=>{
      this.aircraftDB =  data;
   });
  ...
}