【发布时间】:2018-03-31 10:40:54
【问题描述】:
我想从服务获取输入的最大长度(执行 http 调用以获取值)。
有没有办法只调用一次服务?
<input type="text" [attr.maxLength]="getMaxLength()/>
【问题讨论】:
标签: javascript angular typescript rxjs observable
我想从服务获取输入的最大长度(执行 http 调用以获取值)。
有没有办法只调用一次服务?
<input type="text" [attr.maxLength]="getMaxLength()/>
【问题讨论】:
标签: javascript angular typescript rxjs observable
您可以从服务中获取 max 的值并将其存储在本地值中,并且可以直接绑定到元素。
请在链接中找到示例
https://plnkr.co/edit/FX2DH96Femf02XwBUeCO
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
Quantity (between 10 and 100):
<input type="number" name="quantity" min="{{min}}" max="{{max}}">
<br/>
Name (max length - 10 character)
<input type="text" name="name" [attr.maxLength]="maxTextLen">
</div>
`,
})
export class App {
name:string;
min : number;
max : number;
maxTextLen;
constructor() {
this.name = `Angular! v${VERSION.full}`
this.min = 10;
this.max = 100;
this.maxTextLen = 10;
}
}
【讨论】:
在你的component.ts
maxLenght:number = 0;
ngOnInit() {
this.service.getMaxLength()
.subscribe(max => {
this.maxLenght = max;
});
}
然后在视图中
<input type="text" [attr.maxLength]="maxLength"/>
【讨论】:
在构造函数期间使用方法调用并更新组件变量
constructor(private _http: Http) {
this.getMaxLength().subscribe(data=>{
console.log(data)
this.maxLength= data;
})
}
getMaxLength(): Observable<number> {
return this._http.get(this._url)
.map((response: Response) => response.json())
.catch(this.handleError);
}
【讨论】:
将 maxLength 属性值设置为在 contructor 或 ngOnInit 中设置的类属性将使其不再调用服务
HTML:
<input type="text" [maxLength]="maxLength"/>
打字稿
maxLength: number;
.....
constructor(private myService: MyService){
this.maxLength = this.myService.getMaxLength();
}
【讨论】: