我有一個簡單的 Angular 2 應用程式正在運行,但我想將訂閱邏輯移動到服務而不是組件。也對任何其他改進持開放態度。
當前的
app.component.ts
import { Component } from '@angular/core';
import { Product, AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'Product Test';
products: Product[] = [];
constructor(private appService: AppService) {
this.loadData();
}
loadData(): void {
this.appService.getProducts().subscribe(
(results) => {
//console.log(results);
this.products = results;
},
(err) => {
console.log(err);
//add to alert logger
}
);
}
}
應用服務.ts
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class AppService {
dataProducts: Product[] = [];
constructor(private http: HttpClient) {}
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>('../assets/products.json');
}
}
export type Product = {
ProductID: number;
ProductName: string;
};
我想要的但沒有回傳資料,盡管它沒有任何錯誤。
app.component.ts
import { Component } from '@angular/core';
import { Product, AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
title = 'Product Test';
dataProducts: Product[] = [];
constructor(private appService: AppService) {
this.loadData();
}
loadData(): void {
this.dataProducts = this.appService.dataProducts;
}
}
應用服務.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root',
})
export class AppService {
dataProducts: Product[] = [];
constructor(private http: HttpClient) {
this.http.get<Product[]>('../assets/products.json').subscribe(
(results) => {
//console.log(results);
this.dataProducts = results;
},
(err) => {
console.log(err);
//add to alert logger
}
);
}
}
export type Product = {
ProductID: number;
ProductName: string;
};
uj5u.com熱心網友回復:
您將不得不在某個地方訂閱組件,否則它將永遠不知道何時獲取資料(當請求完成時)。如果您想將資料存盤在服務中(多個組件需要相同的資料并且可能會更新),您可以使用BehaviorSubject。這將允許您訂閱對變數的任何更改。然后第二個選項應該作業。這仍然需要您訂閱組件,盡管這是您想要避免的,并且對于您所描述的內容來說是不必要的,但仍然是一個選項。
正常的解決方案是使用管道。這樣,您可以將資料存盤在服務中并回傳值。那看起來像
// app.service.ts
getProducts(): Observable<Product[]> {
return this.http.get<Product[]>('../assets/products.json').pipe(
tap((products: Product[]) => this.dataProducts = products),
catchError((err: any) => console.log(err)),
);
}
然后在 app.component.ts
// app.component.ts
loadData(): void {
this.appService.getProducts().subscribe(
(products: Product[]) => this.products = products,
);
}
請注意,該錯誤已在服務中處理。如果你想做其他事情,你總是可以在兩個地方都做。你可以找到一個參考tap,catchError以及更多的在這里,但是你應該學會的主要體會是map,tap,catchError,mergeMap。
對于另一個改進,我發現擁有一個models/包含所有自定義類和介面的檔案夾會更好。這樣每個人都很容易知道 aProduct是什么(如果只有一部分知道型別,就沒有理由輸入)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/409348.html
標籤:
