使用Angular 2,双向绑定在模板驱动的表单中很容易 - 您只需使用香蕉盒语法.您将如何以模型驱动的形式复制此行为?
例如,这是标准的反应形式.让我们假装它看起来比它看起来复杂得多,有很多种不同的输入和业务逻辑,因此比模板驱动的方法更适合模型驱动的方法.
export class ExampleModel {
public name: string;
// ... lots of other inputs
}
@Component({
template: `
<form [formGroup]="form">
<input type="text" formControlName="name">
... lots of other inputs
</form>
<h4>Example values: {{example | json}}</h4>
`
})
export class ExampleComponent {
public form: FormGroup;
public example: ExampleModel = new ExampleModel();
constructor(private _fb: FormBuilder) {
this.form = this._fb.group({
name: [ this.example.name, Validators.required ]
// lots of other inputs
});
}
this.form.valueChanges.subscribe({
form => {
console.info('form values', form);
} …Run Code Online (Sandbox Code Playgroud) 在401响应中完全忽略CatchError.
我有httpInterceptor处理oauth2身份验证.
相关代码是:
import { filter, take, switchMap, map, catchError } from 'rxjs/operators';
//ommited
if (authService.hasRefreshToken()) {
return authService.doRefreshToken().pipe(switchMap(tokenResponse => {
const accessToken = tokenResponse['access_token'];
this.tokenSubject.next(accessToken);
return <Observable<HttpEvent<any>>> next.handle(this.addToken(req, accessToken));
}), catchError((err: any, caught: any) => {
console.log(err)
return Observable.throw(err);
})
)
}
Run Code Online (Sandbox Code Playgroud)
AuthService类:
export class AuthService {
doRefreshToken() {
//ommited
return this.httpClient.post(environment.baseUrl + this.tokenEndpoint, null, requestOptions).pipe(
map(tokenResponse => {
this.saveToken(tokenResponse);
return tokenResponse;
}),
catchError((err: any, caught: Observable<Object>) => {
//refreshing token failed (refrech token invalid or expired) redirect to …Run Code Online (Sandbox Code Playgroud) 我定义了一个模型类,我想添加一个枚举标签,如:
export class User {
userID: number;
nom: string;
prenom: string;
dateCretation: Date;
statut: enum {
Value1,
Value2
};
}
Run Code Online (Sandbox Code Playgroud)
枚举中出现标记错误:[ts]预期类型.我该如何解决?
在Angular2中,有没有办法更新矩阵参数,但导航到同一个组件?基本上想要从一个看起来像这样的网址轻松过渡:
/search;term=paris;pageSize=24;currentPage=1;someFilter=value;
同样的事情,但在分页时更新currentPage:
/search;term=paris;pageSize=24;currentPage=2;someFilter=value;
使用router.navigate似乎并不是最佳选择,因为我必须编写大量自己的逻辑来重新构建用于navigate使用的URL (重新构建已经存在的东西).
对于踢腿和咯咯笑,我确实尝试过
this._router.navigate([this._router.url, {currentPage: this.pagination.currentPage}]);
但是(正如你所料),路由器对于当前网址上有矩阵参数这一事实是愚蠢的,所以结果不是很好.
编辑:还应该提到可能有任意数量的矩阵参数的附加键/值对,因此硬编码任何路由都是不可能的
编辑:我以后尝试使用preserveQueryParams: true像:
this._router.navigate(["..", {currentPage: this.pagination.currentPage}], {preserveQueryParams: true});
为了获得一个易于使用/可转移的解决方案,但这并没有保持路线上的矩阵参数.
更新:我已经实现了自己的逻辑来获得所需的行为,所以这里是解决方案的代码片段:
let currentParamsArr: Params = this.route.snapshot.params;
let currentParamsObj: any = { };
for (let param in currentParamsArr) {
currentParamsObj[param] = currentParamsArr[param];
}
currentParamsObj.currentPage = +pageNum; //typecasting shortcut
this._router.navigate([currentParamsObj], { relativeTo: this.route });
Run Code Online (Sandbox Code Playgroud)
这段代码循环遍历参数(因为它们位于快照中),并从中创建一个对象,然后添加/编辑我想要更新的参数,然后导航到"新"路径
但是,这并不漂亮,因为我在程序的许多地方基本上都有相同的逻辑,或者必须对路由器进行修改或提供其他一些通用方法.
我使用Ionic 2,Angular 2和TypeScript构建了一个离子项目来测试框架.我需要在我的项目中包含一个外部库(ntc.js),因为我需要它来命名十六进制颜色.
我知道包含一个Javascript库到TypeScript应该工作,因为JS中的任何工作都适用于TS.我只是不想以错误的方式包含它.
我试图将库添加到www/build/js,但它似乎不起作用,它似乎不是这样做的好方法.我试图寻找方法来做到这一点,但没有发现任何东西(可能是因为Angular 2和Ionic 2仍然是新鲜的).
像 :
import * as ntc from '../../js/ntc';
Run Code Online (Sandbox Code Playgroud)
即使我的图书馆位于正确的地方,似乎也没有效果.TypeScript似乎没有正确读取我的文件,如果它完全读取它.
这样做的好方法是什么?我应该将我的.js文件放在我的项目目录中?
我一直在学习Angular 2,并想知道什么是存储字符串的最佳实践.我在整个应用程序中使用各种字符串:有些字符串直接放在HTML元素中,例如,
// sample.html
<h1>This is my title</h1>
Run Code Online (Sandbox Code Playgroud)
其他字符串存储在绑定到的组件模型中,例如
// boundSample.html
<h1>{{myTitle}}</h1>
// boundSample.component.ts
import ...
@Component({
templateUrl: 'boundSample.html';
})
export class BoundSampleComponent {
myTitle = 'This is another title';
}
Run Code Online (Sandbox Code Playgroud)
我担心的是我的字符串遍布整个应用程序.来自C#/ WPF背景,我习惯将我的字符串保存在一个单独的位置(例如strings.xaml),我可以将其导入代码和UI标记(即用于WPF的XAML,用于Angular的HTML).这极大地有助于可维护性和国际化.
此外,快速浏览角度2的国际化建议使用i18n属性和i18n tool.这假设我的所有字符串都是用HTML定义的,但是如果我想在代码中使用其中的一些字符串呢?
如何以及在何处为Angular2中的字符串定义单个位置,以便我可以在代码中访问这些字符串并使用国际化工具?
我有两个组件,一个使用另一个.
第一个是:"GamePanelComponent" 其中包含html文件:
"my-game-panel-output"tag
第二个是:
import { Component, Input } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'my-game-panel-output',
templateUrl: 'gamepaneloutput.component.html',
styleUrls: [ 'gamepaneloutput.component.css' ]
})
export class GamePanelOutputComponent {
@Input()
message: string;
}
Run Code Online (Sandbox Code Playgroud)
我写了一个测试GamePanelComponent:
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { GamePanelComponent } from './gamepanel.component';
import { GamePanelOutputComponent } from '../gamepaneloutput/gamepaneloutput.component';
describe('GamePanelComponent (inline template)', () => {
let comp: GamePanelComponent;
let …Run Code Online (Sandbox Code Playgroud) 我在Angular2中有一个动态表单.它是一个有4个选择的表单组.此表单还有一个按钮,允许您添加另外4个选项,如下所示:
<form [formGroup]="relationsForm">
<div formArrayName="selectedItems" *ngFor="let item of relationsForm.get('selectedItems').controls; let i=index">
<div [formGroupName]="i">
<div>
<md-select placeholder="Source" formControlName="origin_source" (change)="onChangeOrigin($event, i)">
<md-option *ngFor="let origin of selectedOrigins" [value]="origin.name" >{{ origin.name }}</md-option>
</md-select>
<md-select placeholder="Field" formControlName="field_source">
</md-select>
<md-select placeholder="Source1" formControlName="origin_dest" (change)="onChangeDest($event)" >
<md-option *ngFor="let dest of selectedOrigins" [value]="dest.name" >{{ dest.name }}</md-option>
</md-select>
<md-select placeholder="Field1" formControlName="field_dest">
</md-select>
</div>
</div>
</div>
<button (click)='addRelation()'>ADD RELATIONS</button>
Run Code Online (Sandbox Code Playgroud)
这应该如何工作?当您在第一个选择中选择任何值时,第二个选择必须显示一组具体的项目.
第三个选择具有与第一个选择相同的值,并且具有与第四个选择相关的相同行为.
这组数据是这样的:
this.origins = [{
id: 1,
name: 'origin1',
desc: 'desc1',
columnData: [{ id: 1, name: 'column1' },
{ id: 2, …Run Code Online (Sandbox Code Playgroud) 显然ngfor一个接一个地生成div的分区,当它完成将所有div一个放在另一个上时,呈现一个糟糕的设计,我想得到这样的东西:
[1] [2] [3]
[4] [5] [6]
Run Code Online (Sandbox Code Playgroud)
结果我只有:
[ 1 ]
[ 2 ]
[ 3 ]
and continues..
Run Code Online (Sandbox Code Playgroud)
我的JSON是这样的:
[
{
"id_nivel": "1",
"nombre": "A",
"constelacion": "AA",
"descripcion": "AAAAAAAAAAAAAAAAAAAAA"
},
{
"id_nivel": "2",
"nombre": "B",
"constelacion": "BB",
"descripcion": "BBBBBBBBBBBBBBBBBBBBB"
},
{
"id_nivel": "3",
"nombre": "C",
"constelacion": "CC",
"descripcion": "CCCCCCCCCCCCCCCCCCCCC"
},
{
"id_nivel": "4",
"nombre": "D",
"constelacion": "DD",
"descripcion": "DDDDDDDDDDDDDDDDDDDDD"
},
{
"id_nivel": "5",
"nombre": "E",
"constelacion": "EE",
"descripcion": "EEEEEEEEEEEEEEEEEEEEE"
},
{
"id_nivel": "6",
"nombre": "F",
"constelacion": "FF",
"descripcion": "FFFFFFFFFFFFFFFFFFFF" …Run Code Online (Sandbox Code Playgroud) 我正在使用表格
<form [formGroup]="form">
<input type="text" value={{userDetails.first_name}} formControlName = "firstName">
<button type="submit" data-action="save" (click)="onSubmit(form.value)">
</form>
Run Code Online (Sandbox Code Playgroud)
这里的userDetails.first_name价值是汤姆。它在文本框内的 UI 上可见;但是当我提交表单时form.firstName给了我空值。
angular ×9
javascript ×3
typescript ×3
html ×1
ionic2 ×1
ngfor ×1
reactive ×1
rxjs ×1
string ×1