【问题标题】:updating view automatically using Observable使用 Observable 自动更新视图
【发布时间】:2018-06-05 05:22:31
【问题描述】:

我使用 observable 和 HTTP 请求在服务器上添加数据,然后更新其他路由。

我希望这些数据会立即更新。其实我应该刷新页面来获取新数据

在我的服务中,我使用 AddProj()getAllProj() 函数来获取和发送数据

service.ts

import { Injectable } from "@angular/core";
import { NouveauProjet } from "./models/nouveau-projet";
import { HttpClient, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";

@Injectable()
export class AjoutprojService {
  apiURL = "http://127.0.0.1:8080/api/proj/projets";
  constructor(private http: HttpClient) {}

  getAllProj(): Observable<NouveauProjet[]> {
    return this.http.get<NouveauProjet[]>(
      "http://127.0.0.1:8081/api/proj/projets"
    );
  }
  addProj(nouveauProjet: NouveauProjet): Observable<any> {
  return this.http.post<NouveauProjet[]>(
    "http://127.0.0.1:8081/api/proj/projets",
    nouveauProjet
  );
}
}

ajoutproj.ts 我把数据用addProjet()

addProjet() {
  this.nouveauProjet = {
    ...this.firstFormGroup.value,
    ...this.secondFormGroup.value,
    ...this.thirdFormGroup.value
  };
  this.ajoutProj
    .addProj(this.nouveauProjet)
    .toPromise()
    .then(res => {
      console.log(res.message);
    });
}

在我的 listprojects.ts 文件中,我使用 getAllProj()

获取数据
import { Component, OnInit } from "@angular/core";
import { MatTableDataSource } from "@angular/material";
import { AjoutprojService } from "../ajoutproj.service";
import { NouveauProjet } from "../models/nouveau-projet";

@Component({
  selector: "app-liste-projets",
  templateUrl: "./liste-projets.component.html",
  styleUrls: ["./liste-projets.component.css"]
})
export class ListeProjetsComponent implements OnInit {
  constructor(private ajoutProj: AjoutprojService) {}
  nouveauProjet: NouveauProjet[];
  stateExression: string = "inactive";

  ngOnInit() {
    this.getAllProj();
  }
  displayedColumns = ["Nom projet", "Lead Projet", "effectif"];
  dataSource = new MatTableDataSource<NouveauProjet>(this.nouveauProjet);

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
    this.dataSource.filter = filterValue;
  }

  getAllProj() {
    this.ajoutProj.getAllProj().subscribe(
      response => {
        this.dataSource = new MatTableDataSource<NouveauProjet>(response);
      },
      error => console.log(error)
    );
  }

}

更新我添加了我的模板:

<div class="example-container mat-elevation-z8">
  <div class="example-header">
    <mat-form-field>
      <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
    </mat-form-field>
  </div>

  <mat-table #table [dataSource]="dataSource">

    <ng-container matColumnDef="Nom projet">
      <mat-header-cell *matHeaderCellDef> Nom projet </mat-header-cell>
      <mat-cell *matCellDef="let nouveauProjet"> {{nouveauProjet.nomProj }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="Lead Projet">
      <mat-header-cell *matHeaderCellDef> Lead Projet </mat-header-cell>
      <mat-cell *matCellDef="let nouveauProjet"> {{nouveauProjet.leadProj }} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="effectif">
      <mat-header-cell *matHeaderCellDef> effectif </mat-header-cell>
      <mat-cell *matCellDef="let nouveauProjet"> {{nouveauProjet.pers.length }} </mat-cell>
    </ng-container>



    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>

更新2:我做了一个stackblitz repo,我无法重现服务器端,只是前端

我没有错误,但我的问题是数据没有自动更新。我应该每次都刷新我的页面以获得新的更改,因为我知道我正在使用 Obersables。我忘了什么?

【问题讨论】:

  • 能否也显示您的@Component 的元数据?就你而言,我认为是ListeProjetsComponent。您可能启用了OnPush 更改检测策略。
  • 我没用过 OnPush 不知道是做什么用的
  • changeDetection 是组件元数据对象的属性。长话短说,它改变了 Angular 监听组件变化的方式。这对于提高性能非常有用。您可以阅读 [blog.thoughtram.io/angular/2016/02/22/… here] 了解有关 Angular 中更改检测的更多信息。如果您还没有使用它,那么也许您还应该使用您的模板更新问题,以便我们可以看到那里发生了什么。
  • 要更改的数据是dataSource,并且绑定到mat-table组件?
  • 是的 mat-table 使用 dataSource 变量。我正在使用 Angular Material 库的表格组件material.angular.io/components/table/overview

标签: javascript angular observable angular-observable


【解决方案1】:

对于订阅一个 Obersables 并返回它发出的最新值,你可以尝试使用AsyncPipe

异步管道订阅 Observable 或 Promise 并返回 它发出的最新值。当发出一个新值时,异步 管道标记要检查更改的组件。当组件 被破坏,异步管道自动取消订阅以避免 潜在的内存泄漏。

【讨论】:

  • 如何在我的 sourcedata 变量中使用它?
  • 在模板变量中添加管道异步:{{ variable |异步}}
  • 我收到一个错误:InvalidPipeArgument: 'value' for pipe 'AsyncPipe'
  • 我没有意识到您希望 Material Data Tables 的数据源:Data 成为 Observable。你会在这里找到一个带有“connect(): Observable”的例子:stackblitz.com/edit/…
  • 感谢您的示例,要适应我的示例有点困难,请随时更改我的 stackblitz 存储库
猜你喜欢
  • 1970-01-01
  • 2017-05-04
  • 2023-03-19
  • 2020-09-09
  • 2022-10-28
  • 2013-11-22
  • 2011-12-07
  • 2014-01-14
  • 1970-01-01
相关资源
最近更新 更多