功能部件中实现的服务-httpclient

时间:2019-08-18 10:01:53

标签: angular observable httpclient

我要包括的步骤: 我想使用以下方法填充并显示从数据库获取的表: -Service“ DataService”,带有httpClient的方法getPoints()返回可观察 -父组件“数据导入”,使用方法ImplementTable()从注入的DataService使用服务方法getPoints() 我通过@Input属性绑定到的子组件“ Table-with_data”返回表Points [],模型:Point {x,y}

(我有json-server) *下一个问题是从最近上传的csv文件中获取数据

+我的问题出现在servise的getPoints()方法和我要实现Points []的ImplementTable()之间 +我不知道在“普通类型”和“可观察类型”中绑定父子组件值之间是否有区别

数据导入组件

export class DataImportComponent implements OnInit {
  private points: Point[];
  private pointsObservable: Observable<Point[]>;

  constructor(private dataService: DataService) {}

  implementTable() {
    return this.dataService.getPoints().subscribe((data: Point[]) => {
      this.pointsObservable = data;
    });
  }

  ngOnInit() {
    this.implementTable();
  }
}
<div class="table">
  <br />
  <app-table-with-data [point]="point" [points]="points"></app-table-with-data>
</div>

数据服务

export class DataService {
  baseURL = "http://localhost:3000";

  constructor(private http: HttpClient) {}

  getPoints(): Observable<Point[]> {
    return this.http.get<Point[]>(this.baseURL + "/points");
  }
}

表格组件

export class TableWithDataComponent implements OnInit {
  @Input() point: Point;
  @Input() points: Observable<Point[]>;

  constructor() {}

  ngOnInit() {}
}
<tbody>
  <tr *ngFor="let point of points | async">
    <td>{{ point.x }}</td>
    <td>{{ point.y }}</td>
  </tr>
</tbody>

我的另外一个问题是:如果我要上传文件并将其保存到服务器,那么如何使注入UploaderComponent的UploaderService正常工作,因为我接下来要做的是以表格形式(带有数据的表格)创建此文件我在上面解释了。 Doest uploadFile和seveToServer方法是两个单独的操作,还是第二个是第一个的一部分?这是我的代码:

export class UploaderService {

   baseURL = 'http://localhost:3000';

   constructor(private http : HttpClient) {}

   public uploadFile( file: File ): Observable<any> {
      return this.http.post(this.baseURL+'uploaded', file );
   }


constructor( uploaderService: UploaderService ) { }

   public uploadFile( file: File ) {
        this.uploaderService.uploadFile(file);

   }

  public postOnServer(file: File){
        this.uploaderService.uploadFile(file);
    }

<input
  #fileInput
  type="file"
  class="upload__input"
  (change)="uploadFile( fileInput.file) ; fileInput.value = null;"
/>
<button (click)="postOnServer(fileInput.file)">Save file</button>

我试图以身作则,这让我感到困惑。

1 个答案:

答案 0 :(得分:0)

您的问题一定是您传递了Point[],但表组件期望Observable<Point[]>

因此您可以按以下方式更改父组件:

export class DataImportComponent {
  public points$: Observable<Point[]>;

  constructor(private readonly dataService: DataService) {
    this.points$ = this.dataService.getPoints();
  }
}
<div class="table">
  <br />
  <app-table-with-data [points]="points$ | async"></app-table-with-data>
</div>

在这里您将订阅points$在顶部的组件,并将值向下传递给子组件(使它们变笨)。

因此表组件可能是:

export class TableWithDataComponent {
  @Input() points: Point[];
}
<tbody>
  <tr *ngFor="let point of points">
    <td>{{ point.x }}</td>
    <td>{{ point.y }}</td>
  </tr>
</tbody>