# AngularJS2OfficialDemo **Repository Path**: justinchou/AngularJS2OfficialDemo ## Basic Information - **Project Name**: AngularJS2OfficialDemo - **Description**: No description available - **Primary Language**: TypeScript - **License**: MIT - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2016-08-28 - **Last Updated**: 2020-12-19 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README 涉及知识点 === 1. 入口文件为index.html 其中加载了app目录 System.import('app').catch(... 定义了标签 2. 在app目录中, 执行了默认文件 main.ts 其中加载了AppModule import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); 3. 在app.module.ts文件中, 进行了 3.1 核心模块加载 3.2 引用自定义模块 3.3 通过@angular/core加载核心模块和自定义模块 核心模块加入到imports数组中, 重写的路由模块也要放在imports中 Component加入到declarations数组中, 入口Component还要加入到bootstrap数组中 Service加入到providers数组中 4. 执行在所有的Component 执行顺序 4.1 调用 constructor 4.2 如果有Service注入器, 将初始化注入器变量 4.3 如果class继承于OnInit, 将执行 ngOnInit(){} 中的内容, 异步 4.4 将 selector = "my-app" Component中的template 或 templateUrl 中的内容显示到index.html的标签中 4.5 依次将Component中selector对应的template内容塞到对应标签中 5. 涉及的代码 模块: core 核心模块 NgModule, Component, Input, OnInit, Injectable forms 表单 FormsModule router 路由 Routes, RouterModule 语句 {{ 变量, 表达式 }} *ngFor="let v of value" *ngFor="let v of service.getValue()" *ngIf="selectedValue" [(ngModule)]="selectedValue.name" html 标签与 selector = 'my-app' 对应 (click)="onClickFunc(v)" [class.selected]="value === selectedValue" 6. 将网页一部分剥离出去到另外的Component中 html 将原有代码生成新的html template, 并命名selector, 假设为 my-part 在原有代码处添加html标签 与selector同名 数据引入 Component 中把html中用到的数据定义出来 @Input() hero: Hero; 数据注入 在原有html处, 注入数据 将新的Component写入到declarations中 7. Service注入 同步 // Service中定义 getHeroes(): Hero[] { return HEROES; } // Component中使用 constructor(private service: HeroService) { heroes: Hero[] = this.service.getHeroes(); } 异步 // Service中定义 getHeroesAsync(): Promise { return Promise.resolve(HEROES); } // Component中使用 heroes: Hero[]; constructor(private service: HeroService){} ngOnInit(){ this.service.getHeroesAsync().then(heroes => (this.heroes = heroes)); } 将新的Service写入到providers中 8. Router 路由 index.html 在head中, 添加 添加导航栏 添加路由代码 const routing = [ {path: "uri", component: 组件}, {path: "uri", redirectTo: "uri", pathMatch: 'full'} ]; export const routing = RouterModule.forRoot(appRoutes); uri: 支持 xx/yy/zz, 和变量 xx/:userid 使用路由 使用路由的Component要注入路由 constructor(private router: Router){} 路由跳转 this.router.navigate(['/detail', hero.id, hero.name]); 返回上个页面: window.history.back(); 获取路由传参, 其中路由应该写成 '/detail/:id/:name' this.router.params.forEach((params: Params) => { let id = params['id']; let name = params['name']; }); ** 路由跳转的参数数量要和路由定义的参数数量相同 ** this.router.navigate(['/detail', hero.id, hero.name]); path: '/detail/:id/:name', ... 9. Http 请求