Angular基础笔记(架构)

384 阅读2分钟

模块(ngModule)

一个ngModule就是一个容器,用于存放一些组件,服务或其他代码文件,作用是提供一个编译上下文环境。

@NgModule({
  declarations: [],//可声明对象表
  imports: [],//导入表
  exports:[],//导出表
  providers: [],//服务
  bootstrap: []//主视图
})

它也可以导入其它模块的功能,导出一些功能供其它模块使用。

import {Component} from '@angular/core';//从@angular/core库导入Component装饰器
export class AppModule { }//导出模块

组件(component)

组件控制屏幕上被称为视图的一小块区域。组件扮演着控制器和视图的角色,模板则扮演视图的角色。作用是通过在类中定义组件的属性方法与视图交互。

//dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import {Hero} from '../hero';
import {HeroService} from '../hero.service';
@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {
  heroes:Hero[];
  constructor(private heroService:HeroService) { }

  ngOnInit() {
  	this.getHoures()
  }
  getHoures():void{
  	this.heroService.getHeroes()
  	.subscribe(heroes => this.heroes = heroes.slice(1,5))
  }

}


//dashboard.component.html
<h2>Top Heroes!</h2>
<div class="grid grid-pad">
	<a *ngFor='let hero of heroes' class='col-1-4' routerLink = '/detail/{{hero.id}}'>
		<div class='module hero'>
			<h4>{{hero.name}}</h4>
		</div>
	</a>
</div>
<app-hero-detail *ngIf="selectedHero" [hero]="selectedHero"></app-hero-detail>

模板语法

a.数据绑定

  • {{hero.name}}插值表达式
  • [hero]属性绑定;
  • (click)事件绑定;
  • [(ngModel)]双向数据绑定

b.管道

@pipe可以自定义,也可以用Angular自带的管道,用来在模板中声明显示值的转换逻辑,相当于filter。在html中用管道操作符|。比如

{{interpolated_value | pipe_name}}

c.指令

模板可以根据指令对dom进行转换,组件其实也是指令,是一个带有@directive装饰器的类。

结构型指令

<li *ngFor="let hero of heroes"></li>

属性型指令

<input [(ngModel)]="hero.name">

服务与依赖注入

狭义的服务是一个明确定义了用途的类。Angular把组件和服务分开,组件只负责数据绑定的属性和方法,组件不负责从服务器获取数据、验证用户输入、写日志,这是服务要做的,然后注入到任意组件。

@Injectable({
  providedIn: 'root'
})
export class HeroService {
  getHeroes ():Observable<Hero[]>{
  	this.messageService.add('HeroService:fetched heroes')
  	return this.http.get<Hero[]>(this.heroesUrl)
  	           .pipe(
  	           		tap(heroes => this.log(`fetched heroes`)),
  	           		catchError(this.handleError('getHeroes',[]))
  	           	)
  };
  constructor(
  	private http:HttpClient,
  	private messageService:MessageService
  ) { }
}

依赖注入(DI) 要用任何类都必须用注入器注册一个提供商,以便注册器可以使用它来创建新实例。注入器是主要的机制,不用自己创建。