本文總結一下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.