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 ...
随机推荐
- Oracle 三大范式
范式:数据库设计对数据的存储性能,还有开发人员对数据的操作都有莫大的关系.所以建立科学的,规范的的数据库是需要满足一些.规范的来优化数据数据存储方式.在关系型数据库中这些规范. 第一范式:数据库表中的 ...
- vue路由守卫应用,监听是否登录
路由跳转前做一些验证,比如登录验证,是网站中的普遍需求. 对此,vue-route 提供的 beforeRouteUpdate 可以方便地实现导航守卫(navigation-guards). 导航守卫 ...
- Git的安装和创建版本库
1.Git是分布式版本控制系统 2.安装Git 下载Git后,按照默认设置即可实现安装,安装完毕后点击git目录下的Git Bash 输入以下命令符: git config --global user ...
- CSS知识点(一)
一.引入CSS样式(重点掌握) 行内样式 内接样式 外接样式 3.1 链接式 3.1 导入式 css介绍 现在的互联网前端分三层: HTML:超文本标记语言.从语义的角度描述页面结构. CSS:层叠样 ...
- volatile原理解析
Java并发编程:volatile关键字解析 volatile 有序性.可见性 volatile可以保证一定程度上有序性,即volatile前面的代码先于后面的代码先执行. 但是前.后代码,各自里面的 ...
- Spring之缓存注解@Cacheable
https://www.cnblogs.com/fashflying/p/6908028.html https://blog.csdn.net/syani/article/details/522399 ...
- Python之简单的用户登录和注册
# -*- coding: utf-8 -*- # @Time : 2018/7/26 20:16 # @Author : Adam # @File : exam2.py # @Project: ke ...
- 每天进步一点点out1
1● attend ətend 2● infant əfənd
- jquery自定义类的封装
如何用jquery自定义一个类?(demo参考) /*简单使用*/ (function($){ //el操纵对象,option属性值 $.love = function(el,option){ var ...
- MAVEN 创建 JAR项目
从Maven模板创建一个项目 在终端或命令提示(windows)中,浏览到要创建JAVA项目的文件夹下 键入如下命令: mvn archetype:generate -DgroupId={projec ...