angular 学习日志
1、创建项目
npm install -g @angular/cli ng new my-app cd my-app
ng serve --open // 或者 npm start
2、生成新模块
ng generate component heroes
3、引入双向绑定模块儿 app.module.ts 中添加
import { FormsModule } from '@angular/forms'
// @NgModule 中
imports: [
BrowserModule,
FormsModule
]
4、父组件和子组件的交互
父页面中:
<app-hero-detail [hero]="selectedHero" ></app-hero-detail>
子组件中:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-hero-detail',
templateUrl: './hero-detail.component.html',
styleUrls: ['./hero-detail.component.css']
})
export class HeroDetailComponent implements OnInit {
@Input() hero
constructor() {
console.log('===>',this.hero)
}
ngOnInit() {
}
}
5、生成service
ng generate service hero //--module=app 限定service 作用的等级
6、类promise 更好的 “订阅”
// 生成
getHeros(){
return of([{
id: 1,
age: 33,
name: '小花'
},{
id: 2,
age: 33,
name: '小花'
},{
id: 3,
age: 33,
name: '小花'
},{
id: 4,
age: 33,
name: '小花'
},{
id: 5,
age: 33,
name: '小花'
},{
id: 6,
age: 33,
name: '小花'
}])
} // 订阅
this.hService.getHeros().subscribe(res=>{
this.heros = res;
})
7、添加路由
// --flat 把这个文件放进了 src/app 中,而不是单独的目录中。
// --module=app 告诉 CLI 把它注册到 AppModule 的 imports 数组中。
ng generate module app-routing --flat --module=app // 修改src/app/app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router'
import {HerosComponent} from './heros/heros.component'; const routes: Routes = [
{path: 'heros',component:HerosComponent}
] @NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { } // 修改app.component.html 添加
<router-outlet></router-outlet>
<!-- routerLink方式 -->
<div routerLink="/detail/{{h.id}}" *ngFor="let h of heroList" >
{{h.name}}
</div>
// 获取参数
this.route.snapshot.paramMap.get('id')
// 路由配置 写法
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{path: 'heros',component:HerosComponent},
{path: 'detail/:id',component:HeroDetailComponent},
{path: 'home',component:DashboardComponent}
]
8、HttpClient
// 引入 httpClient
import { HttpClient, HttpHeaders } from '@angular/common/http'; // Service 中
private heroesUrl = 'api/heroes'; // URL to web api const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
}; /**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead // TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result.
return of(result as T);
};
} constructor(
private http: HttpClient,
private messageService: MessageService) { } /** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(heroes => this.log(`fetched heroes`)),
catchError(this.handleError('getHeroes', []))
);
} /** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((hero: Hero) => this.log(`added hero w/ id=${hero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
} //
9、 搜索请求的处理 及 异步请求的 处理
控制器:
import { Component, OnInit } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {
debounceTime, distinctUntilChanged, switchMap
} from 'rxjs/operators';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ]
})
export class HeroSearchComponent implements OnInit {
heroes$: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(private heroService: HeroService) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes$ = this.searchTerms.pipe(
// wait 300ms after each keystroke before considering the term
debounceTime(300),
// ignore new term if same as previous term
distinctUntilChanged(),
// switch to new search observable each time the term changes
// 只会返回最近一次 http请求的数据,会取消之前请求队列
switchMap((term: string) => this.heroService.searchHeroes(term)),
);
}
}
html:
<div id="search-component">
<h4>Hero Search</h4> <input #searchBox id="search-box" (keyup)="search(searchBox.value)" /> <ul class="search-result">
<li *ngFor="let hero of heroes$ | async" >
<a routerLink="/detail/{{hero.id}}">
{{hero.name}}
</a>
</li>
</ul>
</div>
angular 学习日志的更多相关文章
- angular学习资源
angular学习资源 angularjs库: https://developers.google.com/speed/libraries/devguide?hl=zh-CN#angularjs ...
- GRE学习日志
发现开博客园真的很有督促作用,今天也顺便开个GRE学习日志吧 2015-02-09:单词 2015-02-10:单词 2015-02-11:单词 2015-03-02:阅读 2015-03-04:阅读 ...
- Cortex-M3学习日志(六) -- ADC实验
上一次简单的总结了一下DAC方面的知识,好吧,这次再来总结一下ADC方面的东东.ADC即Analog-to-Digital Converter的缩写,指模/数转换器或者模拟/数字转换器.现实世界是由模 ...
- Cortex-M3学习日志(五) -- DAC实验
终于逮了个忙里偷闲的机会,就再学一下LPC1768的外围功能吧,循序渐进是学习的基本规则,也许LPC1768的DAC与8位单片机16位单片机里面集成的DAC操作类似,但是既然这是懒猫的学习日志,就顺便 ...
- webpack2学习日志
webpack说容易也容易,说难也难,主要还是看个人,想学到什么样的程度,很多公司可能要求仅仅是会用就行,但是也有一些公司要求比较高,要懂一些底层的原理,所以还是要花一些时间的,看个人需求.这篇仅仅是 ...
- javascript学习日志:前言
javascript学习日志系列的所有博客,主要理论依据是<javascript权威指南>(犀牛书第6版)以及<javascript高级程序设计第三版>(红色书),目前js行业 ...
- MobileForm控件的使用方式-用.NET(C#)开发APP的学习日志
今天继续Smobiler开发APP的学习日志,这次是做一个title.toolbar.侧边栏三种效果 样式一 一. Toolbar 1. 目标样式 我们要实现上图中的效果 ...
- 我的游戏学习日志3——三国志GBA
我的游戏学习日志3——三国志GBA 三国志GBA由日本光荣公司1991~1995所推出<三国志>系列游戏,该作是光荣在GBA上推出的<三国志>系列作品的第一款.本游戏登场武将总 ...
- angular学习一框架结构认识
angular学习所有内容均会与vue以及react框架进行对比. angular学习使用的编译器:webstorm 解决编译器屏蔽node_modules包问题: File-->setting ...
随机推荐
- php值传递和引用传递
1,参数传值方式有两种,第一种是值传递,第二种引用传递.值传递比较简单,也就是在php中,数组是当一个普通变量,值传递是要一个实参的一个拷贝副本,跟实参无关,而引用传递后可以改变实参的值而类的对象是无 ...
- 浅谈table、form 标签
1.<table> 标签 1.1包含的元素 <caption></caption>:表头信息. <tr></tr> :定义一个表格行: &l ...
- Windows Server 2003添加防火墙策略教程
1.开始--控制面板--Windows防火墙 2.启用 选择启用即启动防火墙 3.添加例外 常常启用防火墙,还是希望某端口能被某些IP所访问,而防火墙默认是禁止所有IP访问本机的所有端口的,此时我们就 ...
- pl/sql 如何将Excel文件数据导入oracle的数据表?
1.准备导入数据的excel文件 注意:excel列名和数据表列名必须相同,excel文件sheet2和sheet3可以删除 1)excel文件格式 2)数据表格式 2.打开pl/sql ,找到工具- ...
- Win10系列:UWP界面布局基础11
样式继承 为了使样式便于维护及重复使用,可以在一个样式上引用其他的样式,这就是样式继承.样式继承的方法是:在Style元素的BasedOn属性上使用StaticResource标记扩展来引用被继承的样 ...
- unity鼠标滚轮控制摄像机视野的缩放和按住鼠标控制摄像机移动
//摄像机前进后退的速率 private float view_value=20f; private float maximum = 100; private float minmum = 30; / ...
- servlet之中文乱码:request.getParameter()
参考: http://blog.csdn.net/u014558484/article/details/53445178
- shell脚本中出现图形化界面
http://www.ttlsa.com/shell/how-to-create-dialog-boxes-in-interactive-shell-script/
- centos 安装git服务器,配置使用证书登录并你用hook实现代码自动部署
安装git服务器先安装依赖软件:yum -y install gcc zlib-devel openssl-devel perl cpio expat-devel gettext-devel open ...
- vue-router-6-命名视图
//展示多个视图<router-view class="view one"></router-view> <router-view class=&qu ...