typescript - Angular 通過 datePipe 顯示帶有非同步資料的日期
我終於能夠透過這個教學顯示我所有的非同步資料:https://coryrylan.com/blog/using-angular-forms-with-async-data
唯一存在的問題是我從我的 Postgres 資料庫收集所有數據,而日期在這樣的請求後被保存或到達,例如:dateOfBirth: "1997-12-24 00:00:00.0"
我應該說,我想用它來預先填充用於更新用戶檔案的輸入欄位。
我知道 Angular 不能這樣處理,我需要一個 datePipe 或其他東西,但當我用這個來訪問我的資料時,我真的不知道該怎麼使用它:
export class ProfileComponent implements OnInit {
ngOnInit() {
this.buildForm();
this.user = this.userService.getProfile().pipe(
tap(user => this.editForm.patchValue(user))
);
}
public buildForm() {
this.editForm = this.form.group({
username: ['', [Validators.required, Validators.minLength(this.minLength), CustomValidators.validateCharacters], AlreadyTakenValidator.checkUsername(this.registrationService)],
email: ['', [Validators.required, Validators.email, CustomValidators.validateCharacters], AlreadyTakenValidator.checkEmail(this.registrationService)],
oldPassword: ['', [Validators.required], CustomValidators.checkPassword(this.registrationService)],
newPassword: ['', [Validators.required, CustomValidators.passwordStrength]],
newPasswordConf: ['', [Validators.required]],
firstname: ['', [Validators.required, NoWhitespaceValidator()]],
lastname: ['', [Validators.required, NoWhitespaceValidator()]],
country: ['', [Validators.required]],
dateOfBirth: ['', [Validators.required]],
gender: ['', [Validators.required]],
}
, {
validator: MustMatch('newPassword', 'newPasswordConf')
})
}
}
export class User {
userId: number;
username: string;
email: string;
password: string;
firstname: string;
lastname: string;
token?: string;
dateOfBirth: Date;
gender: string;
country = [] as Array<string>;
profileImage;
lastUpdated: Date;
activated: boolean;
}
分叉自原始想法的 StackBlitz,展示它如何與普通日期一起運作: https://stackblitz.com/edit/angular-2wcq3q?file=src/app/app.component.html
同樣有問題的是,我希望通過 i18n 插件根據所選語言更改輸入類型的日期格式。
在我的註冊元件中,我是透過以下方式讓它運作的:
constructor(
private translateService: TranslateService,
private _adapter: DateAdapter<any>
) { }
ngAfterContentChecked() {
this._adapter.setLocale(this.translateService.currentLang);
但是對於從伺服器請求的非同步資料,這不起作用。因為什麼都沒有顯示出來。
編輯:所以也許讓我解釋一下:問題出現的原因是伺服器(在我的案例中是 Postgres 資料庫)傳回一些客戶端無法立即使用的資料。在 Postgres 中,它被儲存為 不含時區的時間戳記,例如:2019-06-13 10:26:09.322
在我的伺服器中,我這樣保存客戶的到達日期:
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDateTime lu = LocalDateTime.parse(lastUpdated, inputFormatter);
LocalDateTime dob = LocalDateTime.parse(dateOfBirth, inputFormatter);
this.dateOfBirth = Date.from(dob.atZone(ZoneOffset.UTC).toInstant()); // both are type Date
this.lastUpdated = Date.from(lu.atZone(ZoneOffset.UTC).toInstant());
我瀏覽了 StackOverflow 上的許多討論串,並且看到大家都說時區非常麻煩,而且你應該把日期以 UTC 儲存到資料庫中。但是如果我把它們儲存為 timestamp with time zone 呢?這會解決 Angular/用戶端無法立即處理到達的日期的問題嗎?我真的想保持目前預先填充輸入欄位的方式,但用這個方法我無法改變日期,或者我就是不知道該怎麼做。