尝试建立表单,但由于某种原因,尽管使用[[ngModel)],但我的html中的Date输入未绑定到对象的日期值
的HTML:
<input type='date' #myDate [(ngModel)]='demoUser.date'/><br>
表单组件:
export class FormComponent {
demoUser = new User(0, '', '', '', '', new Date(), '', 0, [], []);
}
用户类别:
export class User {
constructor (
public id: number,
public email: string,
public password: string,
public firstName: string,
public lastName: string,
public date: Date,
public gender: string,
public weight: number,
public dietRestrictions: string[],
public fitnessGoals: string[]
){
}
}
测试输出显示当前的“新”日期作为对象的值,但是输入不会更新User对象的日期值或反映该值,表明双向绑定都不起作用。 帮助将不胜感激。
迁移到TS 2.2.2后,此错误开始弹出,因此我认为这是问题所在。代码并未停止工作,但是现在我收到了该错误,并尝试了一些操作,例如返回可观察到的空值 ,捕获重新抛出的异常并返回对象,似乎没有任何效果。 为什么现在会发生这种情况? 它不应该理解我要重新抛出异常并且不期望返回吗? 我在读错误吗?
这是完整的错误描述:
这是完整的代码:
return request
.map((res: Response) => res.json())
.catch((error: any) => {
// todo: log?
if (error.status == 500) {
this.alertService.showError(error.statusText);
} else if (error.status == 588) {
this.alertService.showAlert(error.statusText);
}
Observable.throw(error.statusText);
});
我尝试返回Observable,但是我的包装方法期望返回类型T
,这是我的反序列化请求(map(...)
)的返回值。 如果我确实返回throw
,这是我得到的错误:
[ts]类型“可观察”不能分配给类型“ T”
我正在使用:
- 角4
- 打字稿2.2.2
我正在使用最新的Angular CLI,并创建了一个自定义组件文件夹,该文件夹包含所有组件。
例如,TextInputComponent
具有TextInputConfiguration
类,该类放置在system.config.js
内部,而在我使用它的src/app/home/addnewuser/add.user.component.ts
中有:
import {TextInputConfiguration} from "../../../components/configurations";
很好,但是随着我的应用程序变得越来越大,system.config.js
增加,我该如何处理?
以前,对于SystemJS,我将通过以下方式配置通过system.config.js
的路径:
System.config({
..
map : {'ng_custom_widgets':'components' },
packages : {'ng_custom_widgets':{main:'configurations.ts', defaultExtension: 'ts'},
)};
如何使用Angular CLI为webpack生成相同的内容?
我花了一些时间阅读Typescript语言规范,并对内部和外部模块之间的差异感到有些困惑。 这是直接来自规范的描述:
内部模块(第9.2.2节)是其他模块(包括全局模块和外部模块)的本地或导出成员。 内部模块使用指定其名称和主体的ModuleDeclarations进行声明。 具有多个标识符的名称路径等效于一系列嵌套的内部模块声明。
外部模块(第9.4节)是使用外部模块名称引用的单独加载的代码体。 外部模块被编写为一个单独的源文件,其中至少包含一个导入或导出声明。 另外,可以使用全局模块中的AmbientModuleDeclarations声明外部模块,该声明直接将外部模块名称指定为字符串文字。 这将在第0节中进一步描述。
根据我的理解,我认为外部模块对应于打字稿文件,而没有包含仅导出一组类型和/或变量的模块定义。 从另一个打字稿文件中,我可以使用import foo = module("foo");
简单地在foo.ts中导入外部模块
有人可以向我解释外部模块和内部模块之间的区别吗?
在我的Angular应用中,我有一个组件:
import { MakeService } from './../../services/make.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-vehicle-form',
templateUrl: './vehicle-form.component.html',
styleUrls: ['./vehicle-form.component.css']
})
export class VehicleFormComponent implements OnInit {
makes: any[];
vehicle = {};
constructor(private makeService: MakeService) { }
ngOnInit() {
this.makeService.getMakes().subscribe(makes => { this.makes = makes
console.log("MAKES", this.makes);
});
}
onMakeChange(){
console.log("VEHICLE", this.vehicle);
}
}
但是在“ makes”属性中,我有一个错误。我不知道该怎么办...
我需要上传一个文件并发送一些json,我有这个功能:
POST_formData(url, data) {
var headers = new Headers(), authtoken = localStorage.getItem('authtoken');
if (authtoken) {
headers.append("Authorization", 'Token ' + authtoken)
}
headers.append("Accept", 'application/json');
headers.delete("Content-Type");
var requestoptions = new RequestOptions({
method: RequestMethod.Post,
url: this.apiURL + url,
headers: headers,
body: data
})
return this.http.request(new Request(requestoptions))
.map((res: Response) => {
if (res) {
return { status: res.status, json: res.json() }
}
})
}
我的问题是,如果我将content-type
设置为“ multipart/form-data
”,我的服务器会抱怨边界,如果我完全删除content-type
标头,我的服务器会抱怨它“ text/plain
”是受支持的媒体类型。
那么,如何发送带有angular2的FormData?
是否可以从打字稿模块中导出简单功能?
这不是为我编译。
module SayHi {
export function() {
console.log("Hi");
}
}
new SayHi();
这个工作项似乎意味着您不能但不能说清楚。 不可能吗
我常这样声明无状态组件:
const example: React.SFC<IExample> = ({propsType}) => ();
但是,现在不推荐使用SFC,也许Dan Abramov的这个Twitter帖子解释了原因。
SFC已过时,现在应该使用什么?
我有一个数据驱动的Angular应用程序。 我有一个切换组件,该组件在切换状态下传递。 我的问题是,除非我将toggle布尔值作为对象传递,否则双向数据绑定似乎不起作用。 有没有一种方法可以使它工作而无需使用EventEmitter或将变量作为对象传递。 这将是一个可重用的组件,并且应用程序是由大量数据驱动的,因此不能将值作为对象传递。 我的代码是...。
toggle.html
<input type="checkbox" [(ngModel)]="toggled" [id]="toggleId" name="check"/>
toggle.component.ts
import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
moduleId: module.id,
selector: 'toggle-switch',
templateUrl: 'toggle-switch.component.html',
styleUrls: ['toggle-switch.component.css']
})
export class ToggleSwitchComponent {
@Input() toggleId: string;
@Input() toggled: boolean;
}
parent.component.html
<toggle-switch toggleId="toggle-1" [(toggled)]="nongenericObject.toggled"></toggle-switch>
我是开发Angular 4的新手。在从API获得有关显示图像的响应时遇到了问题。在API中,图像文件具有输入流文件,我不知道如何检索和正确显示它。
有人可以解决吗?
我尝试了这个:
Image.Component.ts:
this.http.get('http://localhost:8080/xxx/download/file/596fba76ed18aa54e4f80769')
.subscribe((response) => { var blob = new Blob([response.text()], {type: "image/png"});
console.log(blob);
console.log(window.btoa(blob.toString()));
});
结果=> W29iamVjdCBCbG9iXQ==
,但是格式不正确
并尝试了这个:
this.http.get('http://localhost:8080/xxx/download/file/596fba76ed18aa54e4f80769').map(Image=>Image.text())
.subscribe(data => {
console.log((data.toString()));
});
结果像这样=>
����\ExifII*��7 ��DuckyK��fhttp://ns.adobe.com/xap/1.0/<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?> <x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.3-c011 66.145661, 2012/02/06-14:56:27 "> <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"> <rdf:Description rdf:about="" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stRef="http://ns.adobe.com/xap/1.0/sType/ResourceRef#" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmpMM:OriginalDocumentID="xmp.did:0280117407206811A2188F30B3BD015B" xmpMM:DocumentID="xmp.did:E2C71E85399511E7A5719C5BBD3DDB73" xmpMM:InstanceID="xmp.iid:E2C71E84399511E7A5719C5BBD3DDB73" xmp:CreatorTool="Adobe Photoshop CC 2014 (Windows)"> <xmpMM:DerivedFrom stRef:instanceID="xmp.iid:7092a9cd-b3fd-bb49-b53c-9b6e1aa1ac93" stRef:documentID="adobe:docid:photoshop:40615934-3680-11e7-911d-f07c687d49b8"/> <dc:rights> <rdf:Alt> <rdf:li xml:lang="x-default"> </rdf:li> </rdf:Alt> </dc:rights> <dc:creator> <rdf:Seq/> </dc:creator> </rdf:Description> </rdf:RDF> </x:xmpmeta> <?xpacket end="r"?>���Photoshop 3.08BIMJZ%Gt6 8BIM%�<".}��νz��܌��Adobed����
但是我曾经使用window.btoa进行编码,这应该是错误的,例如不是拉丁范围
TypeScript,-strictNullChecks模式。
假设我有一个可为空的字符串数组(string | null)[]。 用单一表达式以结果为string []的方式删除所有null的方法是什么?
const array: (string | null)[] = ["foo", "bar", null, "zoo", null];
const filterdArray: string[] = ???;
Array.filter在这里不起作用:
// Type '(string | null)[]' is not assignable to type 'string[]'
array.filter(x => x != null);
数组理解可能有效,但TypeScript不支持它们。
实际上,该问题可以推广到通过从联合中删除具有一种特定类型的条目来过滤任何联合类型的数组的问题。 但是,让我们关注具有null且可能未定义的并集,因为这是最常见的用例。
注意:我是Angular的新手,所以请原谅这里的任何新来的愚蠢者。
细节
问题
editor.es5.js:1689未捕获的错误:模块'ProjectsModule'导入了意外的指令'ProjectsListComponent'。 请添加一个@NgModule批注。
应用模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { environment } from '../environments/environment';
import { ProjectsModule } from './projects/projects.module';
import { HttpModule } from '@angular/http';
@NgModule({
imports: [
BrowserModule,
HttpModule,
ProjectsModule,
AngularFireModule.initializeApp(environment.firebase, 'AngularFireTestOne'), // imports firebase/app needed for everything
AngularFireDatabaseModule, // imports firebase/database, only needed for database features
AngularFireAuthModule // imports firebase/auth, only needed for auth features
],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
项目模块
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ProjectsListComponent } from './projects-list.component';
import { RouterModule } from '@angular/router';
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
BrowserModule,
ProjectsListComponent,
RouterModule.forChild([
{ path: 'projects', component: ProjectsListComponent }
])
]
})
export class ProjectsModule { }
我设置模块的过程与使用Angular 2时没有什么不同。但是,在遇到Angular Cli,firebase和angular fire之间的兼容性问题后,我决定获取所有最新信息。 早上。
对此的任何帮助都会得到极大的赞赏,因为我对这一切的理解使自己陷入困境。
谢谢。
(编辑:VS代码;打字稿:2.2.1)
目的是获取请求响应的标头
假设服务中具有HttpClient的POST请求
import {
Injectable
} from "@angular/core";
import {
HttpClient,
HttpHeaders,
} from "@angular/common/http";
@Injectable()
export class MyHttpClientService {
const url = 'url';
const body = {
body: 'the body'
};
const headers = 'headers made with HttpHeaders';
const options = {
headers: headers,
observe: "response", // to display the full response
responseType: "json"
};
return this.http.post(sessionUrl, body, options)
.subscribe(response => {
console.log(response);
return response;
}, err => {
throw err;
});
}
HttpClient Angular文档
第一个问题是我遇到Typescript错误:
'Argument of type '{
headers: HttpHeaders;
observe: string;
responseType: string;
}' is not assignable to parameter of type'{
headers?: HttpHeaders;
observe?: "body";
params?: HttpParams; reportProgress?: boolean;
respons...'.
Types of property 'observe' are incompatible.
Type 'string' is not assignable to type '"body"'.'
at: '51,49' source: 'ts'
确实,当我转到post()方法的ref时,我指出了这个原型(我使用VS代码)
post(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe?: 'body';
params?: HttpParams;
reportProgress?: boolean;
responseType: 'arraybuffer';
withCredentials?: boolean;
}): Observable<ArrayBuffer>;
但是我想要这个重载的方法:
post(url: string, body: any | null, options: {
headers?: HttpHeaders;
observe: 'response';
params?: HttpParams;
reportProgress?: boolean;
responseType?: 'json';
withCredentials?: boolean;
}): Observable<HttpResponse<Object>>;
因此,我尝试使用此结构修复此错误:
const options = {
headers: headers,
"observe?": "response",
"responseType?": "json",
};
并编译! 但是我只是得到json格式的主体请求。
此外,为什么我必须放一个? 字段名称末尾的符号? 正如我在Typescript网站上看到的那样,该符号应该只是告诉用户它是可选的?
我也尝试使用所有字段,不带和带? 分数
编辑
我尝试了Angular 4提出的从API响应获取标头的解决方案。 对于地图解决方案:
this.http.post(url).map(resp => console.log(resp));
Typescript编译器告诉您映射不存在,因为它不是Observable的一部分
我也尝试过
import { Response } from "@angular/http";
this.http.post(url).post((resp: Response) => resp)
它可以编译,但是得到了不受支持的媒体类型响应。这些解决方案应适用于“ Http”,但不适用于“ HttpClient”。
编辑2
@Supamiu解决方案还提供了不受支持的媒体类型,因此标题中将出现错误。 因此,上面的第二个解决方案(具有Response类型)也应该起作用。 但从个性上来说,我认为这不是将“ Http”与“ HttpClient”混合使用的好方法,因此我将保留Supamiu的解决方案
我想创建一个表单,用户可以在其中输入他的电子邮件。 我想验证客户端的电子邮件格式。
Angular 2中是否有任何通用的电子邮件验证程序?
注意:类似于AngularJS验证程序。
我刚刚升级到Angular RC 5,现在当我尝试进行单元测试时,所有使用'ROUTER_DIRECTIVES'的组件都会失败,并显示'无法解析路由器的所有参数:(?,?,?,?,?,?,?)' 组件。
import { inject, addProviders } from '@angular/core/testing';
import { ComponentFixture, TestComponentBuilder } from '@angular/core/testing';
import { Component } from '@angular/core';
import { ROUTER_DIRECTIVES, Router } from '@angular/router';
import { HomeComponent } from './home.component';
import { UserService } from '../_services/user.service';
describe('Component: Home', () => {
beforeEach(() => {
addProviders([HomeComponent, UserService, ROUTER_DIRECTIVES, Router]);
});
it('should inject the component', inject([HomeComponent, UserService, ROUTER_DIRECTIVES, Router],
(component: HomeComponent) => {
expect(component).toBeTruthy();
// expect(component.currentUser.firstname).toEqual('Jan');
}));
完整的错误日志:
Chrome 52.0.2743 (Windows 10 0.0.0)
Error: Can't resolve all parameters for Router: (?, ?, ?, ?, ?, ?, ?).
at new BaseException (webpack:///C:/ng/anbud/~/@angular/compiler/src/facade/exceptions.js:27:0 <- src/test.ts:2943:23)
at CompileMetadataResolver.getDependenciesMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:551:0 <- src/test.ts:24542:19)
at CompileMetadataResolver.getTypeMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:448:0 <- src/test.ts:24439:26)
at webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:594:0 <- src/test.ts:24585:41
at Array.forEach (native)
at CompileMetadataResolver.getProvidersMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:575:0 <- src/test.ts:24566:19)
at CompileMetadataResolver.getNgModuleMetadata (webpack:///C:/ng/anbud/~/@angular/compiler/src/metadata_resolver.js:305:0 <- src/test.ts:24296:58)
at RuntimeCompiler._compileComponents (webpack:///C:/ng/anbud/~/@angular/compiler/src/runtime_compiler.js:150:0 <- src/test.ts:37986:47)
at RuntimeCompiler._compileModuleAndAllComponents (webpack:///C:/ng/anbud/~/@angular/compiler/src/runtime_compiler.js:78:0 <- src/test.ts:37914:37)
at RuntimeCompiler.compileModuleAndAllComponentsSync (webpack:///C:/ng/anbud/~/@angular/compiler/src/runtime_compiler.js:52:0 <- src/test.ts:37888:21)
有什么想法如何通过布线对组件进行单元测试吗?
我正在尝试在typescript中初始化一个对象,该对象需要对“ options”参数使用JSON字符串。 确切地说,这是这里的对象。 options参数必须是JSON字符串,而不是用于初始化dijit的对象。
有没有一种方法可以通过打字稿对象创建JSON字符串,而无需手动操作?
请不要链接任何未明确指出“ TypeScript”的问题,因为该问题与TypeScript特别相关。 尽管JavaScript的派生方式与您编写代码的方式不同,所以这是唯一询问当前与TypeScript有关的问题的帖子。
如何为基本类型(例如数组)添加方法? 在全局模块中,这将被认可
interface Array {
remove(o): Array;
}
但是实际执行情况放在哪里?
我刚刚开始研究一些基本的Angular 4,并且一直听着发出的事件。 这是一个再现问题的最小示例(至少在我看来是这样):
AppComponent
正在“广播”当前日期,然后由其父级<app-date-sender (someStringSent)="dateReceived($event)"></app-date-sender>
处理(请参见下文):
import { Component, Output } from '@angular/core';
import { EventEmitter } from "events";
@Component({
selector: 'app-date-sender',
template: '<button (click)="sendDate()">Send</button>'
})
export class DateSenderComponent {
@Output() dateSent = new EventEmitter();
sendDate(){
var dt = new Date();
console.log(dt);
this.dateSent.emit(dt.toString());
}
}
AppComponent
应该收听广播的日期事件:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: '<app-date-sender (dateSent)="dateReceived($event)"></app-date-sender>'
})
export class AppComponent {
dateReceived(value){
console.log('Result: ', value);
}
}
从各种初学者教程中,我认为这是侦听事件的方式。 但是,加载页面时,不是打印出接收到的日期值,而是出现以下错误:
AppComponent.html:1错误TypeError:instance [output.propName] .subscribe不是一个函数
在createDirectiveInstance(core.es5.js:10727)
在createViewNodes(core.es5.js:12086)
在callViewAction(core.es5.js:12530)
在execComponentViewsAction(core.es5.js:12439)
在createViewNodes(core.es5.js:12113)
在createRootView(core.es5.js:11991)
在callWithDebugContext(core.es5.js:13206)
在Object.debugCreateRootView [作为createRootView](core.es5.js:12666)
在ComponentFactory_.create(core.es5.js:9912)
在ComponentFactoryBoundToModule.create(core.es5.js:3448)
不幸的是,我无法找到任何有关这实际上意味着什么的信息,而且我也无法自行解决。
似乎暗示着一件事:当我更改AppComponent
模板以侦听未在任何地方发出的某个事件(例如<app-date-sender (someStringSent)="dateReceived($event)"></app-date-sender>
)时,错误消失了。 因此,实际输出事件与侦听该事件的模板之间似乎存在联系,这似乎是问题的原因。
谁能指出我正确的方向?
因此,这似乎应该是一件容易的事,但它开始让我发疯。 我似乎无法关闭TSLint或TS或引起我这些错误的任何东西。 我只希望ESLint具有自己配置的规则,别无其他。
它内置在TS中吗? 我禁用了TSLint扩展名(甚至将其卸载了)。 我设置了以下规则:
"typescript.format.enable": false,
"typescript.validate.enable": false,
仍然给我错误。 如何关闭此功能?
我们正在Angular 2和TypeScript中构建一个应用程序。 我们尝试在可能的情况下静态检查类型。 有什么方法可以检查模板中的类型? 考虑以下片段:
<foo [data]="dataObj"></foo>
假设Foo
组件中的data
具有某种TData
类型。但是,默认情况下,没有什么阻止我传递不符合TData
的dataObj
。Angular模板是否有打字稿扩展名,可以在这种情况下验证类型?