簡體   English   中英

如何在 MEAN 堆棧中使用服務?

[英]How to use services in MEAN stack?

問題

我正在處理大量數據,當使用 RouterLink 在組件之間傳遞時,它會通過 MongoDB 的服務回調數據庫,因此這對用戶來說是一個糟糕的體驗

代碼

--機構.component.ts

 listInstitutions: Institution[] = [];

getInstitution() {
    this._institutionService.getInstitutions().subscribe((data) => {
      this.listInstitutions = data;
    });
  }

--機構.service.ts

 getInstitutions(): Observable<any> {
    return this.http.get(this.url);
  }

解決方案

為了讓它通過 Link 路由器在組件之間傳遞而不重新加載 getInstitutions() 方法,我在服務中創建了所有內容,包括數據列表,即從機構.component.ts 到機構.service.ts 和我只在機構.component.html 中調用我的 crud 服務中的列表

_serviceInstitution.listIntituations

有了這個,我現在可以在組件之間導航,這樣就不會每次都調用數據庫方法。

結論

這是一種有效的方法嗎? 你有什么問題? 可以嗎? ,我在其他地方看到他們只使用開頭所說的語法。 非常感謝

您需要緩存這些值,僅當您確定 API 只需要在您的應用程序中執行一次時才執行此操作。 下面我使用AsyncSubject來緩存響應。

import { Injectable, OnDestroy } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AsyncSubject, Observable, of, Subscription } from 'rxjs';
import { map, switchMap } from 'rxjs/operators';

const API_URL = 'https://reqres.in';
@Injectable({
  providedIn: 'root',
})
export class ApiService implements OnDestroy {
  asyncSubject: AsyncSubject<any>;
  subscription: Subscription = new Subscription();

  constructor(private http: HttpClient) {}

  public get(url): Observable<any> {
    return this.http.get(API_URL + '/api/' + url).pipe(map((res) => res));
  }

  public getAsync(url): Observable<any> {
    if (!this.asyncSubject) {
      this.asyncSubject = new AsyncSubject();
      this.subscription.add(
        this.http.get(API_URL + '/api/' + url).subscribe((response) => {
          this.asyncSubject.next(response);
          this.asyncSubject.complete();
        })
      );
    }
    return this.asyncSubject.asObservable();
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}
// /api/users

堆棧閃電戰

參考這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM