js中写html innderhtml,angular2项目实践汇总-1

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中添加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中

6e7a09115b89f2a67845d53da1c75928.png

logout0.png

这次请求不能被拦截,否则会报403错误

logout1.png

第二次发出了post请求

有数据返回了

ac4c59f50fe3b5be0f84af5603e555fd.png

logout2.png

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方法

042023f0fe6c502514a9e0221ffffc9d.png

2.png

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指令不支持键值对{}结构数据

解决方法:写个管道处理数据

...

@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监听循环结束事件,使用指令

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= new EventEmitter();

ngOnInit(): void {

if (this.isLast) {

this.lastDone.emit(true);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值