在Angular 6的服务中使用http时无法读取未定义的属性“ get”

时间:2019-03-04 11:33:01

标签: angular http service

我有两项服务。一种是核心服务,另一种是特定服务。 在核心服务中,我发出http请求。在Angular 6中,它不起作用。 (在Angular 7中效果理想)。

在Angular 6中,我得到无法读取http上未定义的属性'get'

这是我的代码:

query-service.ts

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

@Injectable({
  providedIn: 'root'
})

export class QueryService {
  protected apiUrl: string = 'http://localhost:4200';

  constructor(private http: HttpClient) {}

  public query(uri: string): Observable<any> {
    const url = this.apiUrl + '/' + uri;

    return this.http.get(url, {responseType: 'json', withCredentials: true});
  }
}

client-search.service.ts

import {Injectable} from '@angular/core';
import {Client} from '../models/client';
import {Observable} from 'rxjs';
import {QueryService} from '../services/query.service';
import {map} from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})

export class ClientSearchService extends QueryService {

  public list(uri: string): Observable<any> {
    const clientResponse = this.query(uri);

    return clientResponse.pipe(
      map(data => data.collection),
      map((records: Client[]) => records.map((client: Client) => Client.factory(client)))
    );
  }

}

client-search.component.ts

import {Component, OnInit} from '@angular/core';
import {Client} from '../models/client';
import {ClientSearchService} from './client-search.service';
import {ClientsShareService} from '../services/clients-share.service';

@Component({
  selector: 'app-crm-client-search',
  templateUrl: './client-search.component.html',
  styleUrls: ['./client-search.component.css']
})

export class ClientSearchComponent implements OnInit {
  public client: Client = new Client();
  public clientList: Client[];

  constructor(public clientSearchService: ClientSearchService, public clientsShareService: ClientsShareService) {
  }

  ngOnInit() {

    const clientsList = this.clientSearchService.list('assets/files/clients.json');

    clientsList.subscribe((clients: Client[]) => {
      this.clientList = clients;
      this.clientsShareService.setData(clients);
    });

  }

}

1 个答案:

答案 0 :(得分:1)

您的子类只有默认的构造函数,而父类没有默认的构造函数。因此,angular会创建ClientSearchService的实例而不会注入HttpClient服务。

实际上,您当前拥有这个:

ClientSearchService extends QueryService {
  constructor(){
    super();
  }
}

您需要向子类添加非默认构造函数,如下所示:

export class ClientSearchService extends QueryService{
 constructor(http: HttpClient){
   super(http)
 }
 ...
}