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 ...
随机推荐
- 【微信公众号开发】【10】JSJDK相关
前言: 1,优点:官方提供的,会调用后还算使用方便,不用费劲了解各个原生组件 缺点:使用上有限制(如:上传文件有大小限制),很容易踩坑,部分安卓手机及电脑端不支持pjax 总结:上手容易,坑很多 2, ...
- 数据结构与算法之PHP实现二叉树的遍历
一.二叉树的遍历 以某种特定顺序访问树中所有的节点称为树的遍历,遍历二叉树可分深度优先遍历和广度优先遍历. 深度优先遍历:对每一个可能的分支路径深入到不能再深入为止,而且每个节点只能访问一次.可以细分 ...
- 操作远程RabbitMQ
1.连接远程RabbitMQ 访问 http://your ip address:15672 通用帐号为guest,密码为guest:也可以使用自己创建的账号 注:your ip address只你 ...
- C++类型检查
与大多数语言一样,C++也是类型决定了能对该对象进行的操作,一条表达式是否合法依赖于其中参与运算的对象的类型,C++是一种静态数据类型语言,它的类型检查发生在编译时, 因此编译器知道程序中每一个变量对 ...
- python http 请求 响应 post表单提交
1. 查看请求 响应情况 print(response.text) print(response.headers) print(response.request.body) print(respons ...
- zhuan 常用图像数据集:标注、检索
目录(?)[+] 1.搜狗实验室数据集: http://www.sogou.com/labs/dl/p.html 互联网图片库来自sogou图片搜索所索引的部分数据.其中收集了包括人物.动物. ...
- git Please move or remove them before you can merge.
git clean -d -fx "" 其中 x -----删除忽略文件已经对git来说不识别的文件 d -----删除未被添加到git的路径中的文件 f -----强制运行
- Linux内核空间内存申请函数kmalloc、kzalloc、vmalloc
我们都知道在用户空间动态申请内存用的函数是 malloc(),这个函数在各种操作系统上的使用是一致的,对应的用户空间内存释放函数是 free(). 注意:动态申请的内存使用完后必须要释放,否则会造成内 ...
- redis客户端windows版中文乱码解决方案
1.在cmd窗口,在redis-cli.exe 后加上--raw 2.修改cmd窗口编码 http://jingyan.baidu.com/article/e75aca85440f01142edac6 ...
- 【转载】sprintf()函数 和 printf()函数
sprintf()函数 和 printf()函数 参考:C++ 中的sprintf和snprintf 函数的区别 - CSDN博客 http://blog.csdn.net/youbingchen/ ...