我通过http获取日期时间,并想在使用之前对其进行格式化。为此,我使用了get和set方法,但是set方法从未被调用。
我的组件(AdminComponent):
import { Component, OnInit } from '@angular/core';
import { AdminService } from './admin.service';
import { Config } from './_config';
@Component({
selector: 'app-admin',
templateUrl: './admin.component.html',
styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {
config: Config = new Config();
constructor(private adminService: AdminService) { }
ngOnInit() {
this.getConfig();
}
getConfig(): void { //THIS IS THE IMPORTANT PART FOR THIS QUESTION
this.adminService.getConfig().subscribe(config => {
this.config = config;
console.log(this.config); //just to debug
});
}
saveConfig(): void {
//here will come the save
}
}
AdminService:
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { Config } from './_config';
@Injectable({
providedIn: 'root'
})
export class AdminService {
private getConfigUrl = '//../getConfig.php';
private saveConfigUrl = '//../saveConfig.php';
constructor(private http: HttpClient) {
this.getConfigUrl = window.location.protocol+this.getConfigUrl;
this.saveConfigUrl = window.location.protocol+this.saveConfigUrl;
}
getConfig(): Observable<Config> {
var data = ""; //is used but not necessary for this example.
var headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
return this.http.post<Config>(this.getConfigUrl, data, { headers: headers } ).pipe(catchError(this.handleError('admin getConfig', [])));
}
saveConfig(config: Config) {
var data = "config="+JSON.stringify(config);
var headers = new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded'});
return this.http.post<string>(this.saveConfigUrl, data, { headers: headers } ).pipe(catchError(this.handleError('admin saveConfig', [])));
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
和Config类(在这里我使用get和set方法):
export class Config {
title: string;
_startdate: Date;
enddate: Date;
public get startdate(): string {
console.log("get called");
return this.parseDateToStringWithFormat(this._startdate);
}
public set startdate(v: string) {
console.log("set called");
let actualParsedDate = v ? new Date(v) : new Date();
let normalizedParsedDate = new Date(actualParsedDate.getTime() + (actualParsedDate.getTimezoneOffset() * 60000));
console.log("from: "+v+" to: "+normalizedParsedDate);
this._startdate = normalizedParsedDate;
}
private parseDateToStringWithFormat(date: Date): string {
//formats the date-string to be usable in the input type="datetime-local"
return date.toISOString().substring(0,16);
}
}
我将startdate
的名称更改为_startdate
,并为startdate
创建了一个获取和设置方法。在我的模板中,我对输入字段使用了双重绑定,例如:<input type="datetime-local" [(ngModel)]="config.startdate">
在我的控制台上,从未调用set方法,但调用了get方法。调用this._startdate
时未定义。所以我想我从根本上做错了。
我的目标是不必处理组件中的日期格式,我想直接在Config类中进行操作。
编辑:如果我从AdminService更改函数getConfig()
来分别设置每个有效的变量,请参见此处:
getConfig(): void {
this.adminService.getConfig().subscribe(config => {
this.config.title = config.title;
this.config.startdate = config.startdate;
this.config.enddate = config.enddate;
console.log(this.config);
});
}
由于Config只有3个变量,所以这没什么大不了的,但是在较大的类中,这并不是我真正想要的。我也不确定为什么第一个版本不起作用?
答案 0 :(得分:1)
我知道为什么现在不对它进行任何设置...当代码中的值设置为
时,将调用SETgetConfig(): void { //THIS IS THE IMPORTANT PART FOR THIS QUESTION
this.adminService.getConfig().subscribe(config => {
this.config = config; // this is where you are calling GET
config.startdate = 'foo'; // this is a SET example
console.log(this.config);
});
}
编辑:
如果您的代码太大,则可以在Config类中使用 constructor :
class Config {
private title: string;
private startdate: string;
private enddate: string;
constructor(title: string, startdate: string, enddate: string) {
this.title = title;
this.startdate = startdate;
this.enddate = enddate;
}
// ... getters/setters
}
我认为这是在打字稿中使用类的最佳方法