Angular-cli 构建应用
的一些配置
标签(空格分隔): Angular
直接使用 ng build --prod --build-optimizer --base-href=/ 来发布
base-href可以设置服务器上的某个子路径,使用 ng build --base-href=/my/path/
如果打包静态文件(js和css)不放在和index.html同一路径下,可以在.angular-cli.json配置文件apps属性下增加deployUrl,等同于webpack的publicPath。
如遇刷新找不到页面(404)的情况,需要在服务器配置重定向到index.html。以nginx为例,可以在location添加try_files $uri $uri/ /index.html?$query_string;来重定向到index.html。
如果碰到 *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引用是不行的。
首次项目实践问题记录
1. node版本升级(v6.x.x -> v8.11.1)后,原来项目ng serve抛出错误:Node Sass could not find a binding for your current environment。
此时需要执行npm rebuild node-sass来解决。参见stackoverflow。
2. 想要在整个应用初始化时候,在路由导航之前就请求数据,可以通过APP_INITIALIZER实现。
app.module.ts
export function loadToken(tokenService: InitDataService) {
return () => tokenService.tokenAndTime();
}
providers: [
...
{
provide: APP_INITIALIZER,
useFactory: loadToken,
deps: [InitDataService],
multi: true
},
...
],
*值得一提的是,目前只实现了同步数据获取,如果异步,并不能在路由渲染完毕之前获取完成。有待研究。 *
3. 关于querySelector()选择器,默认是返回Element,这时候就不能在其后用.style了。
需要将选择到的Element转为HTMLElement(参见):
let overlay = document.querySelector(`#${this.ID}`);
overlay.style.display = 'none';
4. 关于angualr的HttpClient,post请求默认将body中的数据序列化为json,如果后台只接收urlencoded格式的数据,就不能直接传对象了:
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;
}
}
5. 如果想要使组件样式可以应用到子组件,可以通过
@Component({
encapsulation: ViewEncapsulation.None,
...
})
这时样式将不再局限于当前组件。
6. 如果想要当前根路径(子根路径)导航到未匹配路由时,比如设置404,可以在路由数组的末尾添加
const ROUTES: Routes = [
...
{ path: '**', component: NotFoundComponent}
];
7. 关于polyfills.ts
之前没有取消注释这个文件中的引用,在IE下打开发现报错,取消注释第一块引用后,发现所有浏览器都出现自定义DI抛出错误Uncaught Error: Can't re