Angular V4.0 几个应用场景

来源:互联网 发布:金相检验软件系统 编辑:程序博客网 时间:2024/06/14 01:04

1. Http 跨域

    使用http 无法跨域访问,报错:“No 'Access-Control-Allow-Origin' header is present on the requested resource”

    解决方法可以在服务器端加 必须在response中添加 Access-Control-Allow-Origin 的header;

    或者使用 jsonp,或者在服务器端做反向代理。

2. 后台更新数组,ngFor 没有更新 view

    使用 ngZone 来更新数组,参考:https://stackoverflow.com/questions/31706948/angular2-view-not-changing-after-data-is-updated

    

import {NgZone} from 'angular2/angular2';import {SocketService} from 'js/services/SocketService';export class MyService {    zone:NgZone;    myList:Array<string> = [];    socketSvc:SocketService;    constructor() {        this.zone = new NgZone({enableLongStackTrace: false});        this.socketSvc = new SocketService();        this.initListeners();    }    getData() {        this.socketSvc.emit('event');    }    initListeners() {        this.socketSvc.socket.on('success', (data) => {            this.zone.run(() => {                this.myList = data;                console.log('Updated List: ', this.myList);            });        });    } }

3. 获取当前页面的 url 地址

    使用 @angular/common/Location 的 path() 只能取得除主机外的路径,不包含域名及端口号。

    可以直接在代码中调用 window.location,angular 的 typescript 文件中,可以直接访问 window 对象的方法及属性,无须 import 或注入。

    如 alert, location, document 等


4. url query string encoding

    如上,直接使用 window  的方法encodeURIComponent

 console.log(encodeURIComponent(location.href));

5. unsafe:url

    当使用跨站 URI 资源时,如图片,链接等,使用数据绑定,会自动被加上 unsafe:

    可以使用 import { DomSanitizer } from "@angular/platform-browser" 声明可信任网址。

    参考:https://angular.cn/docs/ts/latest/guide/security.html#!#bypass-security-apis


6. 调用第三方 js 库

    a) 在 index.html 中包含 <script src=...

    b) 定义 xxx.d.ts

    c) 在 ts 文件头加入 /// <reference path="../dt/xxx.d.ts"/>

    比如要定义一个函数,可以在 xx.d.ts 中写:

    declare function jsSHA(a:any, b:any):void;

    参考:http://www.gyzhao.me/2016/04/30/VsCodeTypings/

        http://www.typescriptlang.org/docs/handbook/namespaces.html



阅读全文
0 0