标签(空格分隔): Angularjavascript
ng build --prod --build-optimizer --base-href=/
来发布base-href
能够设置服务器上的某个子路径,使用 ng build --base-href=/my/path/
.angular-cli.json
配置文件apps
属性下增长deployUrl
,等同于webpack的publicPath
。如遇刷新找不到页面(404)的状况,须要在服务器配置重定向到index.html。以nginx为例,能够在location添加try_files $uri $uri/ /index.html?$query_string;
来重定向到index.html。php
若是碰到 *ngIf
*ngFor
用不了得状况,好比抛出 Property binding ngForOf not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations".的错误,一般是由于没有importCommonModule
,并且这个import必须在组件被引用的module
中。好比我把routes
和modules
分离,这样组件将会在xx-routing.module.ts
中被import,那么这个CommonModule
就得在xx-routing.module.ts
中被import,在xx.module.ts
引用是不行的。css
ng serve
抛出错误:Node Sass could not find a binding for your current environment。此时须要执行npm rebuild node-sass
来解决。参见stackoverflow。html
APP_INITIALIZER
实现。app.module.tsvue
export function loadToken(tokenService: InitDataService) { return () => tokenService.tokenAndTime(); } providers: [ ... { provide: APP_INITIALIZER, useFactory: loadToken, deps: [InitDataService], multi: true }, ... ],
querySelector()
选择器,默认是返回Element
,这时候就不能在其后用.style
了。须要将选择到的Element转为HTMLElement(参见):java
let overlay = <HTMLElement>document.querySelector(`#${this.ID}`); overlay.style.display = 'none';
private init() { this.url = apiData.ServiceUrl + this.path; const datas: Datas = { ClientType: apiData.ClientType, Token: this.tokenDatasService.token }; Object.assign(datas, this._datas); // 将参数对象序列化为 [key1]=[value1]&[key2]=[value2]的字符串 let params = new HttpParams(); if (!this.isGet) { datas.Timespan = this.tokenDatasService.timespanFormat; } for (let key in datas) { params = params.set(key, datas[key]); } if (this.isGet) { this.datas = { params: params }; } else { this.datas = params; } }
参见node
@Component({ encapsulation: ViewEncapsulation.None, ... })
这时样式将再也不局限于当前组件。webpack
const ROUTES: Routes = [ ... { path: '**', component: NotFoundComponent} ];
polyfills.ts
以前没有取消注释这个文件中的引用,在IE下打开发现报错,取消注释第一块引用后,发现全部浏览器都出现自定义DI抛出错误Uncaught Error: Can't resolve all parameters for ApiService: (?). at syntaxError (compiler.es5.js:1694) ...。css3
google了半天都是说没写@Injectable()
或者少@或者(),然而检查了半天并非。最后在GitHub的一个Issues中找到了答案,须要取消注释import 'core-js/es7/reflect';
便可解决。缘由暂且未去探究。nginx
使用@ViewChild('[name]') canvasRef: ElementRef
来选择canvas画布。
background: url("/assets/img/shared/logo.png") no-repeat center/100%;
父级提供服务支持(providers),父级在constructor方法中订阅(subscribe),子路由在ngOnInit方法或者其余自定义事件中赋值(next)。
能够经过setTimeout([callback], 0)异步处理结果实现参见GitHub Issues :
this.accountService.titles$.subscribe(titles => setTimeout(() => { this.title = titles.title; this.titleLink = titles.titleLink.link; this.titleLinkName = titles.titleLink.name; }, 0));
以nginx为例:
location / { root C:\Web\Site; index index.html; ry_files $uri $uri/ /index.html?$query_string; }
v-if
和v-else
,ng中也有这样的模板语法:注意必须使用ng-template
。
<h2 class="nick-name" *ngIf="isLogin; else notLogin">{{ userInfo.Name }}</h2> <ng-template #notLogin> <a href="javascript: void(0);" class="nick-name">当即登陆</a> </ng-template>
Subject
实现组件之间的通讯ionic中有一个Events
服务,能够经过publish
发布事件,在其余组件中subscribe
事件。
在Angular项目中,咱们能够经过Subject
来建立一个服务实现相似的效果。类同本文(# 10)所述。
import {Injectable} from '@angular/core'; import {Datas} from '../models/datas.model'; import {Subject} from 'rxjs/Subject'; import {Observable} from 'rxjs/Observable'; import {Subscriber} from 'rxjs/Subscriber'; @Injectable() export class EventsService { private events: Datas = {}; public eventsName = []; constructor() { } /** * 发布 * @param {string} topic 事件名称 * @param {Datas} params 参数(对象) */ public publish(topic: string, params: Datas = {}) { const event = this.getEvent(topic); Object.assign(params, { EVENT_TOPIC_NAME: topic }); event.next(params); } /** * 订阅事件 * @param {string} topic 事件名称 * @return {Observable} */ public subscribe(topic: string) { return this.getEvent(topic).asObservable(); } /** * 取消订阅事件 * @param {Subscriber} subscriber 订阅事件对象 */ public unsubscribe(subscriber: Subscriber<any>) { subscriber.unsubscribe(); } private getEvent(topic: string) { this.eventsName.push(topic); this.eventsName = Array.from(new Set(this.eventsName)); let _event; for (const i in this.events) { // 判断是否已有事件 if (this.events.hasOwnProperty(i) && i === topic) { _event = this.events[i]; break; } } if (!_event) { // 没有事件 建立一个 _event = new Subject<Datas>(); const eventObj = { [topic]: _event }; Object.assign(this.events, eventObj); } return _event; } }
... constructor(private eventsService: EventsService) { } ngOnInit() { const a = this.eventsService.subscribe('setHeader').subscribe(v => { console.log(v); // 取消订阅 this.eventsService.unsubscribe(a); }); } ...
... export class IndexComponent implements OnInit { constructor(private eventsService: EventsService) { } ngOnInit() { // 第一次触发 this.eventsService.publish('setHeader', { a: 1, b: 2 }); setTimeout(() => { // 第二次触发 this.eventsService.publish('setHeader', { c: 3 }); }, 5000); } }
在控制台,咱们能够看到:
第二次触发并无被打印。是由于调用了取消订阅事件。将取消订阅事件注释掉,能够看到第二次触发打印:
常常会用到路由跳转后执行一些操做。经过Route
来进行操做。
import {NavigationEnd, Router} from '@angular/router'; ... constructor(private router: Router) { } ... // 导航 navWatch() { this.router.events.subscribe(e => { if (e instanceof NavigationEnd) { // TODO 路由跳转完毕 } }); } ...
使用@Output() [eventName] = new EventEmitter<T>();
,而后在组件内部经过this[eventName].emit([params])
来触发事件、传递参数。组件外部经过圆括号<my-component (eventName)="watchEvent($event)"></my-component>
。其中$event
就是传递过来的参数。
能够经过宿主监听器@HostListener([event]: string, [args]: string[])
来操做。
好比监听window滚动事件:
... @HostListener('window:scroll', []) onWindowScroll() { // TODO 滚动事件 // this.scrollEvent().subscribe(obj => { // this.scrollStyle(obj.offset, obj.direction); // }); } ...
如何实现两次输入密码一致(两个输入框值相等)的自定义验证器。
data-*
等属性直接使用方括号你会发现抛出错误。这时候能够加个attr
来解决:
<img [attr.data-src]="value">
rem
的使用咱们习惯使用 html { font-size: 62.5%; }
来做为根大小(10px),可是Chrome并不支持12px如下的大小,这将致使Chrome与其余浏览器显示不一样。
搜索解决方案。
body { font-size: 1.4em; }
,经试验不起做用(至少在个人项目中)。-webkit-transform: scale(.8, .8);
,不是很满意。html { font-size: 625%; }
,至关于100px。我更偏向于第三种。
若是想要手动配置webpack来打包项目:(非必要)
使用ng new my-app
初始化的项目并不包含webpack配置文件,须要ng eject
命令来加入webpack.config.js
配置文件。
注意此时不能再用 ng build 之类的命令了,开发环境是npm start
,打包命令是npm run build
。
这时候webpack缺乏一些原来的配置。
uglifyjs-webpack-plugin
js压缩插件将js文件压缩,减少打包后文件的体积。
const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); ... new UglifyJsPlugin({ "test": /\.js$/i, "extractComments": false, "sourceMap": true, "cache": false, "parallel": false, "uglifyOptions": { "output": { "ascii_only": true, "comments": false }, "ecma": 5, "warnings": false, "ie8": false, "mangle": { properties: { regex: /^my_[^_]{1}/, reserved: ["$", "_"] } }, "compress": {} } })
compression-webpack-plugin
生成gzip文件插件进一步减少打包文件体积。
const CompressionWebpackPlugin = require('compression-webpack-plugin'); ... new CompressionWebpackPlugin()
这个须要服务器开启gzip on;
,以nginx为例,须要为服务器进行如下配置:
conf/nginx.conf:
http { include mime.types; default_type application/octet-stream; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; #tcp_nopush on; #keepalive_timeout 0; keepalive_timeout 65; # 开启gzip gzip on; gzip_static on; gzip_min_length 1k; gzip_buffers 4 16k; gzip_comp_level 2; gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png; gzip_vary on; gzip_disable "MSIE [1-6]\."; server { listen 8088; server_name localhost; location / { root website/angular; index index.html; } } }
clean-webpack-plugin
清除打包文件工具每次npm run build
后都会生成新的打包文件(文件名添加hash),这个插件能够在打包后删除以前旧的文件。
const CleanWebpackPlugin = require('clean-webpack-plugin'); ... new CleanWebpackPlugin(['dist'], { root: projectRoot, verbose: true, dry: false })
src/assets/
文件夹下的静态资源以及favicon.ico
文件也须要打包,这时须要修改一下自动生成的配置代码:
new CopyWebpackPlugin([ { "context": "src", "to": "assets/", "from": "assets" }, { "context": "src", "to": "", "from": { "glob": "favicon.ico", "dot": true } } ], { "ignore": [ ".gitkeep", "**/.DS_Store", "**/Thumbs.db" ], "debug": "warning" }),
若是须要分离css单独打包,可使用 extract-text-webpack-plugin
。
可能会有解决方案,暂时不作深刻探究。仍是推荐直接使用ng-cli。
注意,分离css后,angular的特殊选择器将失效,好比:host {}
选择器,使用正常的css方法实现来替代。
注意,样式的引用就须要经过import './xx.scss';
的方式来引用样式文件,不然会抛出Expected 'styles' to be an array of strings.
的错误。
也有经过"use": ['to-string-loader'].concat(ExtractTextPlugin.extract(<options>))
的方法来实现。
由于不经过@Component({ styleUrls: '' })
的方式,样式的scope做用将消失。
webpack.config.js
:
const ExtractTextPlugin = require('extract-text-webpack-plugin'); const extractCSS = new ExtractTextPlugin('[name].[contenthash:8].css'); const extractSCSS = new ExtractTextPlugin('[name].[contenthash:8].css'); module.exports = { ... "entry": { ... "styles": [ "./src/app.scss" ] }, "module": { "rules": [ { "test": /\.css$/, "use": extractCSS.extract({ "fallback": "style-loader", "use": [ { "loader": "css-loader", "options": { "sourceMap": false, "import": false } }, { "loader": "postcss-loader", "options": { "ident": "postcss", "plugins": postcssPlugins, "sourceMap": false } }] }) }, { "test": /\.scss$|\.sass$/, "use": extractSCSS.extract({ "fallback": "style-loader", "use": [ { "loader": "css-loader", "options": { "sourceMap": false, "import": false } }, { "loader": "postcss-loader", "options": { "ident": "postcss", "plugins": postcssPlugins, "sourceMap": false } }, { "loader": "sass-loader", "options": { "sourceMap": false, "precision": 8, "includePaths": [] } }] }) }, ], "plugins": [ ... extractCSS, extractSCSS ] } ... }
app.component.ts
import './app.component.scss'; @Component({ selector: 'app-root', templateUrl: './app.component.html' })
publicPath
属性,能够设置资源引用路径,须要写在output
属性下:module.exports = { ... "output": { "publicPath": '/', "path": path.join(process.cwd(), "dist"), "filename": "[name].bundle.[chunkhash:8].js", "chunkFilename": "[id].chunk.[chunkhash:8].js", "crossOriginLoading": false }, ... }
若是使用ng-cli,能够在apps
属性下设置deployUrl
,等同于publicPath。
个人环境
Angular CLI: 1.6.7 (e)
Node: 8.11.1
OS: win32 x64
Angular: 5.2.3
***
demo源码
参考文章: angular-cli issues | style-loader issues | stackoverflow | copy-webpack-plugin拷贝资源插件等
The end... Last updated by: Jehorn, Sep 17, 2018, 04:29 PM