加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular V4.0 几个应用场景

发布时间:2020-12-17 09:12:57 所属栏目:安全 来源:网络整理
导读:1. Http 跨域 使用http 无法跨域访问,报错:“No 'Access-Control-Allow-Origin' header is present on the requested resource” 解决方法可以在服务器端加必须在response中添加 Access-Control-Allow-Origin 的header; 或者使用 jsonp,或者在服务器端做

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读