簡體   English   中英

如何在 Ionic Angular 應用程序中將函數引用為模板變量?

[英]How to refer a funtion as a template variable in Ionic Angular app?

我有一個Order object 和一個客戶 Object。 Order object 的JSON payload如下所示:

{
  "order_number" : 1,
  "customer_id": 1
}

這是Customer object 的JSON payload

{
  "customer_id": 1,
  "customer_name" : 1,
}

我有訂單頁面,我想在其中顯示訂單列表。 但不是order.customer_id而是顯示customer_name

對於我有getCustomerById ,它將customer_id作為參數並返回customer_name

這是我的OrdersPage class:

import { Component, OnInit } from '@angular/core';
import { OrderService } from '../../services/order.service';
import { Order } from '../../models/order.model';
import { NavController, LoadingController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { CustomerService } from 'src/app/services/customer.service';
import { Customer } from 'src/app/models/customer.model';

@Component({
  selector: 'app-orders',
  templateUrl: './orders.page.html',
  styleUrls: ['./orders.page.scss'],
})
export class OrdersPage implements OnInit {
  sender;
  customerName: string;
  destinationName: string;
  // viewOrders = false;
  error;
  orders: Order[];
  subscription: Subscription;
  constructor(private orderService: OrderService,
              private navCtrl: NavController,
              private router: Router,
              private customerService: CustomerService
            ) { }

  ngOnInit() {
    this.orderService.refreshNeeded
      .subscribe(() => {
        this.getAllOrders();
      });
    this.getAllOrders();

  }

  getAllOrders() {

    this.orderService.getAllOrders().subscribe(
      (res: Order[]) => {
        this.orders = res;

      },
      (error) => {
        this.error = error;

      });
  }

  getCustomerById(customerId: number): string {

    this.customerService.getCustomerById(customerId).subscribe(
      (customer: Customer) => {
        this.customerName = customer.name;
      }
    );
    return this.customerName;
  }

}

這是orders.page.html

<ion-header>
  <ion-toolbar color="dark">
    <ion-button slot="end">
      <ion-menu-button> </ion-menu-button>
    </ion-button>
    <ion-title>Orders</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <ion-row>
    <ion-col size-md="8" offset-md="2">
      <ion-row class="header-row ion-text-center">
        <ion-col>
          Order number
        </ion-col>
        <ion-col>
          Customer
        </ion-col>
      </ion-row>
      <ion-row *ngFor="let order of orders; let i = index" class="data-row ion-text-center">
        <ion-col>
          {{order.order_number}}
        </ion-col>
        <ion-col>
          {{order.customer_id}}
        </ion-col>

        <!-- <ion-col>
        {{getCustomerById(order?.customer_id)}}
      </ion-col> -->
      </ion-row>
    </ion-col>
  </ion-row>
</ion-content>

這個 html 有效,但它返回order.customer_id而不是customer_name我試圖通過以這種方式調用模板中的函數來獲取名稱{{getCustomerById(order?.customer_id)}}不起作用並且控制台中沒有錯誤以及。

在訂單列表中獲取customer_name字段的最佳方法是什么?

這是我的customer.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, Subject } from 'rxjs';
import { Customer } from '../models/customer.model';
import { catchError, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {
  url = 'http://api.mydomain.com';

  constructor( ) { }

  getAllCustomers(): Observable<Customer[]> {
    return this.httpClient.get<Customer[]>(`${this.url}/customers`).pipe();
  }

  getCustomerById(id: number): Observable<Customer> {
    return this.httpClient.get<Customer>(`${this.url}/customer/${id}`).pipe();
  }


}

正如@Muhammad Umair 所提到的,為每個客戶名稱向服務器發出請求並不是一個好的設計。 最好是發出一個請求來獲取所有想要的客戶名稱。 下面的解決方案沒有考慮到這一點。

這里最好使用 pipe。

“pipe 將數據作為輸入並將其轉換為所需的 output。” Angular 文檔

請注意,您獲取 curstomer 名稱的請求是異步的(這就是為什么模板中沒有顯示任何內容),在這里您還需要使用異步 pipe :

<ion-col> 
    {{ order.customer_id | getCustomerName | async }} 
</ion-col>

這是 pipe (您應該將其插入組件模塊的聲明中。

import { Pipe } from '@angular/core';

@Pipe({
  name: 'getCustomerName'
})
export class CustomerNamePipe {

  constructor(private customerService: CustomerService) { }

  transform(userIds, args) {
     return this.customerService.getCustomerById(curstomerId);
  }

}

同樣不是一個很好的解決方案,但鑒於您無法更改 API 中的任何內容的情況。 您可以將文件修改為此。

import { Component, OnInit } from '@angular/core';
import { OrderService } from '../../services/order.service';
import { Order } from '../../models/order.model';
import { NavController, LoadingController } from '@ionic/angular';
import { Router } from '@angular/router';
import { Subscription } from 'rxjs';
import { CustomerService } from 'src/app/services/customer.service';
import { Customer } from 'src/app/models/customer.model';

@Component({
  selector: 'app-orders',
  templateUrl: './orders.page.html',
  styleUrls: ['./orders.page.scss'],
})
export class OrdersPage implements OnInit {
  sender;
  customerName: string;
  destinationName: string;
  // viewOrders = false;
  error;
  orders: Order[];
  subscription: Subscription;
  constructor(private orderService: OrderService,
              private navCtrl: NavController,
              private router: Router,
              private customerService: CustomerService
            ) { }

  ngOnInit() {
    this.orderService.refreshNeeded
      .subscribe(() => {
        this.getAllOrders();
        this.getAllCustomers();
      });

    this.getAllOrders();
    this.getAllCustomers();

  }

  getAllOrders() {

    this.orderService.getAllOrders().subscribe(
      (res: Order[]) => {
        this.orders = res;

      },
      (error) => {
        this.error = error;

      });
  }

  getAllCustomers() {

    this.customerService.getAllCustomers().subscribe(
      (customers: Customer[]) => {
        this.customers = customers;
      }
      (error) => {
        this.error = error;

      });
  }

  getCustomerById(customerId: number): string {
    const customer = this.customers.filter(customer => customer.customer_id === customerId );
    return customer.customer_name;
  }

}

正如@Noelmout 提到的那樣,使用 pipe 我只需稍作改動即可獲得customer_name

這是CustomerNamePipe

import { Pipe, PipeTransform } from '@angular/core';
import { CustomerService } from '../services/customer.service';
import { Customer } from '../models/customer.model';
import { pluck } from 'rxjs/operators';

@Pipe({
  name: 'getCustomerName'
})
export class CustomerNamePipe implements PipeTransform {

  customer: Customer;

  constructor(private customerService: CustomerService) { }

  transform(curstomerId, args) {
    return this.customerService.getCustomerById(curstomerId).pipe(pluck('customer_name'));

  }


}

這是訂單.page.html

<ion-col> 
    {{ order.customer_id | getCustomerName | async }} 
</ion-col>

暫無
暫無

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

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