本文总结一下Angular应用的加载过程大概是怎样的。
- 1)angular.json
{
// ...
"projects": {
"app": {
// ...
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "www",
"index": "src/index.html",
"main": "src/main.ts",
// ...
}
}
}
}
}
}
angular应用启动时会先去加载angular.json,c初始化一些配置;其中这两个参数指定了启动时加载的脚本和页面:
"index": "src/index.html", // 指定启动时显示的页面
"main": "src/main.ts", // 制定启动时首先加载的脚本
- 2)src/main.ts
我们打开main.ts, 可以看到代码如下:
// ...
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));
这里指定了启动加载的模块为AppModule,该模块在app.module.ts文件中所定义。
- 3)AppModule(app.module.ts)
我们打开app.module.ts, 可以看到代码如下:
@NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [
BrowserModule,
IonicModule.forRoot(),
AppRoutingModule,
],
providers: [
// ...
],
bootstrap: [AppComponent]
})
export class AppModule { }
bootstrap参数定义了该模块中的主组件为AppComponent,其在app.component.ts中定义。
-
- AppComponent(app.component.ts)
我们打开app.component.ts, 可以看到代码如下:
@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
// ...
}
其中selector
是template的容器,导入了该Component
对应Module
的模块里的template就可以使用这个template了。
比如这里的selector定义为app-root
, *index.html*里就可以使用该模板了:
<body>
<app-root></app-root>
</body>
- 5)index.html
index.html的默认内容如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>example</title>
<base href="/" />
<meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="format-detection" content="telephone=no" />
<meta name="msapplication-tap-highlight" content="no" />
<link rel="icon" type="image/png" href="assets/icon/favicon.png" />
<!-- add to homescreen for ios -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
</head>
<body>
<app-root></app-root>
</body>
</html>
所以我们可以看到, 应用首先加载的index.html页面, 然后index.html里包含了app-root
这个template, 那么最后显示的就是app-root
里实际编写的内容。
因此Angular应用加载的顺序大致可概括为: (angular.json) -> index.html -> main.ts -> AppModule -> AppComponent -> 替换了实际内容的index.html.