angular2正式版9月15日(中秋节)发布,我从10月份开始入门学习(参考前文入门日志),11月开始项目开发,之后边开发边学习,在此把项目中所遇的问题做个汇总。部分技术解决方案已经在文集中单独讲述,总结中包含非ng2框架内容。
1.当页面报错No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.
解决方法:在index.html的header中添加<basehref='/'>
ng2官网中有对此作专门的讲解
2.跨域
angular2项目中通过设置请求头,或者设置拦截器,可以在请求header中添加access-token(身份验证)
1)set header方式
let headers = new Headers({ 'Content-Type': 'application/json', 'access-token': this.getToken() });
let options = new RequestOptions({ headers: headers });
return this.http.post(request_url[action], params, options)
跨域请求分成两次,第一次是options请求,header参数在access-controller-allow-header中
这次请求不能被拦截,否则会报403错误
第二次发出了post请求
有数据返回了
2)拦截器使用BaseRequestOptions
建个class继承BaseRequestOptions
import {BaseRequestOptions} from "@angular/http";
export class MyRequestOptions extends BaseRequestOptions {
merge (options?: RequestOptionsArgs) : RequestOptions {
let headers = options.headers || new Headers;
if (!headers.get('access-token')) {
headers.append('access-token',localStorage.getItem("AccessToken"));
}
if (!headers.get('Content-Type')) {
headers.append('Content-Type','application/json');
}
options.headers = headers;
return super.merge(options);
}
}
在根模块app.component.ts的providers中引入
import { RequestOptions } from '@angular/http';
providers : [ { provide : RequestOptions, useClass : MyRequestOptions } ]
附带ajax中setHead方法
3.angular2中实现js的innerHtml或者ng1中的ng-bing-html的效果
可以通过Ng2内置指令[innderHtml]="htmlContent"实现,不过有个问题,htmlContent中带有的style样式会被过滤
解决:使用ng2的API DomSanitizer
和ng1中的 $sce.trustAsHtml()功能类似, DomSanitizer提供了bypassSecurityTrustHtml
方法,为html标签添加信任,避免被ng2安全机制过滤
有时候,会发现b、sub、sup、i等自带样式的标签没有效果,可能是标签样式被浏览器或者css文件重置了,通过浏览器开发者模式检查一下。
4.typescript语法下,类似方法会报错
let a = {};
a.b = 1;
改成
a['b'] = 1;
或者(a as any).b = 1;
调用window下方法
function call() {}
window.call() //运行环境报错
改成
window['call'];
或者(window as any).call;
(document.querySelector('.ui-paginator-first') as any).click();
还可以写d.ts声明文件
5.Component定义的变量,只声明没有初始化(后面才赋值),如果在html中用到此变量,会报错,声明变量的同时也要初始化。
6.表单元素中用到[(ngModel)]="name"时,可以用(ngModelChange)事件监听变量name变化,change事件用得不好会导致值不实时,或者代码冗余。
关于表单的双向绑定,后期会考虑写一篇文章专门描述
7.Can't bind to 'ngModel' since it isn't a known property of 'input'?
需要import forms模块到module
建议可以建一个共享模块SharedModule,引入通用的模块、组件,再将SharedModule引入到各个模块中,省去麻烦,Component后指令引入到多个模块中会报错,也用这个方法解决。
SharedModule示例
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import {CalendarModule, PaginatorModule, TreeModule, DropdownModule} from "../../assets/theme/primeng/primeng";
import { UPLOAD_DIRECTIVES } from './directives/uploader/uploader';
import { ScrollDirective } from './directives/scroll.directive';
import { DropdownPipe } from './pipe/primeng-dropdown';
import { DropdownTwoPipe } from './pipe/primeng-dropdown2';
import { SerialNumberPipe } from './pipe/serial-number1.pipe';
import { BypassSecurityTrustHtmlPipe } from './pipe/bypassSecurityTrustHtml.pipe';
import { SparkUeditorComponent } from './components/ueditor.component';
import { StarLightComponent } from './components/star-light/star-light.component';
import { PersonSelectComponent } from './components/person-select/person-select.component';
import { PersonSelectService } from './components/person-select/person-select.service';
@NgModule({
imports: [CommonModule, FormsModule,
CalendarModule, PaginatorModule, TreeModule, DropdownModule
],
exports: [CommonModule, FormsModule,UPLOAD_DIRECTIVES,
CalendarModule, PaginatorModule, TreeModule, DropdownModule,
ScrollDirective,
DropdownPipe,
DropdownTwoPipe,
SerialNumberPipe,
BypassSecurityTrustHtmlPipe,
StarLightComponent,
SparkUeditorComponent,
PersonSelectComponent
],
declarations: [
UPLOAD_DIRECTIVES,
ScrollDirective,
DropdownPipe,
DropdownTwoPipe,
SerialNumberPipe,
BypassSecurityTrustHtmlPipe,
StarLightComponent,
SparkUeditorComponent,
PersonSelectComponent
],
providers: [PersonSelectService],
})
export class ShareModule { }
8.能使用安全操作符的地方都应该使用安全操作符,如{{user?.name}}
谁也不想看到浏览器报错,页面什么都不显示
9.ngFor和ngIf不能在同一标签上使用,否则页面报错,可以在ngFor外层包一个标签,在外层标签中使用ngIf
10.*ngFor指令不支持键值对{}结构数据
解决方法:写个管道处理数据
<div *ngFor="let obj of objs | ObjNgFor">...</div>
@Pipe({ name: 'ObjNgFor', pure: false })
export class ObjNgFor implements PipeTransform {
transform(value: any, args: any[] = null): any {
return Object.keys(value).map(key => value[key]);
}
}
11.ngFor获取元素下标
12.ngFor监听循环结束事件,使用指令
<div *ngFor="let item of currentUser?.frontSet;let last = last;" [isLast]="last" (lastDone)="initVav()"></div>
ngFor-isLast.ts
import { Directive, Input, Output, EventEmitter, OnInit} from "@angular/core";
@Directive({
selector : '[isLast]'
})
export class IsLastDirective implements OnInit {
@Input() isLast: boolean;
@Output() lastDone: EventEmitter<boolean> = new EventEmitter<boolean>();
ngOnInit(): void {
if (this.isLast) {
this.lastDone.emit(true);
}
}
}