为什么异步观察者会循环?

Why async observer comes to loop?

在模板中我使用异步管道:

  {{ constructionObjectsDataService.findbycadnum$() | async }}

服务是:

@Injectable({
  providedIn: "root",
})
export class ConstructionObjectsDataService {
      public findbycadnum$ = (): Observable<any> => {
        return this.httpClient.get(
          `${environment.apiUrl}/${this.URL_PATH}/findbycadnum`,
          {
            params: HttpParamsBuilder.buildQueryParams(
              this.parametersService.constructionObjectDataParameters
                .findbycadastnumberParams
            ),
          }
        );
      };

}

为什么我使用以下方式获得对服务器的请求循环:

 {{ constructionObjectsDataService.findbycadnum$() | async }}

这里有一个例子,其中时间参数每秒从 "async"(模拟)函数更新:

@Component({
  selector: "app-root",
  template: "<div> Time: {{ time | async }}</div>"
})
export class AppComponent {
  time = new Observable<string>((observer: Observer<string>) => {
    setInterval(() => observer.next(new Date().toString()), 1000);
  });
}

这是您正在寻找的行为吗?

您可以看到在这个沙箱上工作:https://codesandbox.io/s/angry-elion-1eb8j?file=/src/app/app.component.ts

更新

如果你想在组件加载时调用它,然后每次你决定调用它,你可以订阅另一个方法 (pullData()) 并在每次你想 "refresh"数据:

@Component({
  selector: "app-root",
  template: `
    <div>Time: {{ findbycadnum }}</div>
    <button (click)="pullData()">Update Value</button>
  `
})
export class AppComponent implements OnInit {

  findbycadnum; 

  constructor(private httpClient: HttpClient) {
  }

  ngOnInit(): void {
    this.pullData().subscribe(res => {
      this.findbycadnum = res;
    },
    err => {
      console.log('ERROR', err);

    });
  }

  pullData(): Observable<any> {
    return this.httpClient.get(
      `${environment.apiUrl}/${this.URL_PATH}/findbycadnum`,
      {
        params: HttpParamsBuilder.buildQueryParams(
          this.parametersService.constructionObjectDataParameters
            .findbycadastnumberParams
        ),
      }
    );
  }
}

希望对您有所帮助。 (我没测试过,因为你自定义的http请求在那个沙箱里测试不了)