javascript - Angular2 ใช้ Pipes ใน Component.js
ฉันกำลังเรียน Angular2 และฉันต้องการจัดรูปแบบตัวเลขโดยเพิ่มเครื่องหมายจุลภาคคั่นหลักพัน จากที่ฉันอ่านมาสามารถทำได้โดยใช้ Pipes แต่ปัญหาคือฉันต้องการจัดรูปแบบตัวเลขแบบโปรแกรมในไฟล์ js ไม่ใช่ใน html (ทำแบบ var | number)
ก่อนอื่นฉันได้ตระหนักแล้วว่าไม่มีท่อ NumberPipe แบบสแตนด์อโลนที่ฉันสามารถใช้งานได้ (แก้ไขฉันถ้าฉันผิด) สิ่งที่คล้ายที่สุดคือ CurrencyPipe ใน @angular2/common ดังนั้นฉันจึงมีบางอย่างแบบนี้:
import { Component } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
@Component({
templateUrl: 'test.component.html',
styleUrls: ['./test.component.scss']
})
export class TestComponent {
public myNumber = 1000;
constructor(private currencyPipe: CurrencyPipe) {
var formatted = this.currencyPipe().transform(this.myNumber, 'MXN', true); // Is this correct?
}
}
แต่มันขว้างข้อผิดพลาดดังต่อไปนี้ให้ฉัน: Unhandled Promise rejection: No provider for CurrencyPipe! ; Zone: angular ;...
ฉันทำอะไรผิดไปหรือ
ขอบคุณล่วงหน้า
ด้วยความนับถือ
คำตอบ #1
สิ่งแรก: คุณต้องประกาศ pipe ของคุณ - เพิ่มมันเข้าไปในส่วน declarations ของ NgModule:
declarations: [CurrencyPipe]
ข้อที่สอง: pipe ไม่ใช่สิ่งที่ฉีดเข้าไปได้ ดังนั้นคุณจึงไม่สามารถนำ instance ของมันมาใช้โดยระบบ dependency injection ของ Angular คุณจำเป็นต้องสร้าง instance ของ pipe นี้ขึ้นมาใหม่ด้วยตนเอง เช่น:
var formatted = (new CurrencyPipe()).transform(this.myNumber, 'MXN', true);
