角类型“ void”不能分配给类型“ any []

时间:2019-01-11 02:26:55

标签: angular

出现以下错误。类型“ void”不可分配给类型“ any []”。我发现了类似的问题,但是我无法弄清楚如何将其应用于我的情况。

不确定错误是在OnInIt函数中还是在行中-> @Input()networks = []

// service.ts

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

     private networks: Profile[] = [];

    constructor(private http: HttpClient){}

     getNetworks(){
       this.http.get<{message: string, profiles: Profile []}>('http://localhost:3000/api/profiles')
     .subscribe((profileData)=>{
         console.log(profileData)
         this.networks = profileData.profiles;
     });
 }

}

// component.ts

  export class NetworkComponent implements OnInit {

    @Input() networks = [];

    constructor(public networkService: NetworkService) { }

    ngOnInit() {
       this.networks = this.networkService.getNetworks()

   }

}

试图将信息从服务传递到组件。网络= []应该分配一个对象数组。

2 个答案:

答案 0 :(得分:0)

  

您的服务的getNetworks()应该仅传递不带订阅的http调用,因为如果您在服务上进行订阅,则只能在服务中访问它,而不能在正在调用的组件上访问它的服务,因为您没有从getNetworks()返回任何信息

服务

如果要为getNetworks()设置显式的返回类型,可以通过指定它:getNetworks(): Observable<any> {...}'any'可以根据您的返回值更改为要为其分配的任何接口。 http通话

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

  ...

  getNetworks() {    
     // Add 'return' and let the component subscribe to its response 
     return this.http.get<{message: string, profiles: Profile []}>('http://localhost:3000/api/profiles');
  }

组件

export class NetworkComponent implements OnInit {

   networks: Profile [] = [];

   ...

   ngOnInit() {
      this.networkService
        .getNetworks()
        .subscribe(networks => this.networks = networks.profiles);   // Subscribe and Initialize the networks variable
   }

}

答案 1 :(得分:0)

当您的this.networkService.getNetworks()类型为networks时,得到该错误的原因是any[]返回空值

不建议您使用代码模式,最好不要调用服务订阅,而返回 Observable

这样做

// service.ts

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

     // private networks: Profile[] = []; <- this is not needed

    constructor(private http: HttpClient){}
     // return the Observbale
     getNetworks(){
       return this.http.get<{message: string, profiles: Profile []}>('http://localhost:3000/api/profiles');
 }

// component.ts

export class NetworkComponent implements OnInit {

    @Input() networks = [];

    constructor(public networkService: NetworkService) { }

    ngOnInit() {
       this.networkService.getNetworks()
        .subsribe((res) => { this.networks = res.profiles; });

   }
}