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 ...
随机推荐
- js定义类
以下是es5标准里定义类的方法: function Point(x,y){ this.x=x; this.y=y; } Point.prototype.toString=function(){ ret ...
- python-django rest framework框架之序列化
序列化与反序列化: 对象 -> 字符串 序列化 字符串 -> 对象 反序列化 rest framework序列化+Form 目的: 解决QuerySet序列化问题 功能:解析 和 过滤 - ...
- Cassandra的commitLog、memtable、 SStable
和关系数据库一样,Cassandra在写数据之前,也需要先记录日志,称之为commitlog,然后数据才会写入到Column Family对应的Memtable中,并且Memtable中的内容是按照k ...
- 时间序列 ARIMA 模型 (三)
先看下图: 这是1986年到2006年的原油月度价格.可见在2001年之后,原油价格有一个显著的攀爬,这时再去假定均值是一个定值(常数)就不太合理了,也就是说,第二讲的平稳模型在这种情况下就太适用了. ...
- myeclipse debug模式 报错source not found
myeclipse debug模式下,启动报错 source not found:SignatureParser.current() line: 解决方法:将debug视图下的右上方的jar有断点的地 ...
- Echarts 简单报表系列四:雷达图
代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF ...
- 【转】JS常用函数整合库 lutils
lutils 此工具包是在 outils 的基础上,加上个人平时收集的代码片段进行的二次整合 outils的GitHub:https://github.com/proYang/outils/blob/ ...
- [LeetCode] 95. Unique Binary Search Trees II(给定一个数字n,返回所有二叉搜索树) ☆☆☆
Unique Binary Search Trees II leetcode java [LeetCode]Unique Binary Search Trees II 异构二叉查找树II Unique ...
- python3线程启动与停止
转自: https://blog.csdn.net/weixin_38125866/article/details/76795462 https://www.cnblogs.com/lcchuguo/ ...
- mac以及centos下安装Elasticsearch 以及权限管理插件
Elasticsearch安装(提前系统需要安装java环境)mac安装 brew install elasticsearch centos安装 下载ElasticSearch安装包,https:// ...