Angular基本架构

Angular 的程序架构

  1. angular的基本架构
    • 组件:是angular应用的基本构建块是一段带有业务逻辑和数据的html
    • 指令:允许向HTML元素添加自定义行为
    • 服务:用来封装可重用的业务逻辑
    • 模块:将应用不同的部分组织成angular可以理解的单元
    • 组件,指令,服务是用来完成功能的,模块用于打包和分发功能
  2. 搭建环境
  • 使用 Angular-cli搭建(内核也是webpack)
  • 安装 angular-cli,使用原生的npm会出现一些问题,使用cnpm安装

cnpm i -g angular-cli

  • 重新运行

ng serve --prod –aot

  • 使用webpack搭建

cnpm i
npm run dev

  • 创建项目,auction是项目的名称

ng new auction


组件

  1. 组件必备元素
    • 装饰器@Component,用于告诉angular如何处理typescript类,包含多个属性,这些属性的值叫做原数据,
    • 模板Template定义外观,告诉angular如何渲染组件
    • 控制器:Controller,是一个普通的typescript类,会被装饰器装饰,包含组件所有的属性和方法,绝大多数的业务逻辑是写在控制器中的
  2. selector定义名称,自定义标签,templateUrl定义组件模板路径
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';
}
  1. 制作一个显示即时时间的组件
export class SitestatComponent implements OnInit {
public currentTime:Date();
  constructor() {
window.setInterval(
()=>this.currentTime=new Date()
,1000)
  }
  ngOnInit() {
  }
}
  1. 数据绑定,将组件中定义的即时时间绑定到HTML中,类似vue
{{ currentTime }}
  1. 双向数据绑定
[{ngModel}]=””

模块

  1. import引入模块需要的文件
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. @NgModule装饰器声明模块
    • declarations声明模块有什么(只能声明组件指令和管道),此时只有一个AppComponent组件
    • imports声明要让应用正常运转还需要什么,这里有浏览器模块,表单模块,http模块提供http服务
    • providers,默认为空,用来声明模块中提供的服务
    • bootatrap声明模块的主组件是什么

启动angular应用

  • main.ts中的基本结构
    1. platformBrowserDynamic这个方法告诉angular使用哪个模块来启动应用
    2. enableProdMode用来关闭angular的开发者模式
    3. environment,导入环境配置
    4. AppModule导入主模块
    5. 如果当前是生产环境调用enableProdMode()方法来关闭angular的开发者模式
    6. 最后调用bootstrapModule()传入AppModule作为启动模块,来启动应用
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { environment } from './environments/environment';
import { AppModule } from './app/app.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule);

你可能感兴趣的:(Angular基本架构)