【async pipe】【 promise】 【Observable】【ngSwitch】【@Injectable】 【HttpClient】

private missionAnnounceSource = new Subject();

Subject是一个特殊的Observable,它允许将值多播给多个观察者.


Loading stuff...

From Anuglar v4 above, we are able to using 'as' with async pipe. This allow as using 'new variable' instead of subscribe to observable.

We also able to use 'else' with '*ngIf', else taks a 'template' which will be displayed when the if expression is not matched.

变量名 + $ 表示:这个变量是 Obeservable


 一个获取当前小时的的 Observable:

//ts
currentHour = new Observable((observer: Observer) => {
  setInterval(() => observer.next(new Date().getHours()), 1000)
})

 


{{ currentHour | async }}

关于 as *ngIf async 的结合,输出: 在页面显示 woot ;当匹配异常,在页面显示 loading


{{ value }}
loading

 as的作用:用变量 value 代替 valueStream

//ts
export class AppComponent {
	public valueStream: Observable;
	// I initialize the app component.
	constructor() {
		this.valueStream = of( "woot !" );
	}
}

fromEvent

创建一个Observable,该Observable发出来自给定事件对象的指定类型事件。

创建一个来自于DOM事件,或者Node的EventEmitter事件或其他事件的Observable。

constructor() {
    fromEvent(document, 'click').subscribe(x => {
        console.log('click', x);
});
}
// 发出dom document上的点击事件,每次点击时,都会在控制台发出 MouseEvent。
// 放在 构造函数里

 


ajax pipe 的可订阅对象: Observable | Promise


of 操作符

constructor() {
    of(1, 2, 3).subscribe(res => {
        console.log(res);
    });
}
// 在控制台会输出 1,2,3

@Component({
  selector: 'my-app',
  template: `
  
  
  
  
You selected : {{value}}

1. Template - {{value}}
2. Template - {{value}}
3. Template - {{value}}
Default Template
`, }) export class AppComponent {}

DI

参考: https://blog.csdn.net/zf2014122891/article/details/85335372

依赖注入 providedIn:'root'的原因:如果不在cart.service.ts里加这句话,就需要在根模块@NgModule()参数的providers中注入providers: [CartService] 。我们现在用 providedIn:'root' 的方式。

why DI?

在访问数据的时候, 你通常要对数据做后处理、添加错误处理器,还可能加一些重试逻辑,以便应对网络抽风的情况。

该组件很快就会因为这些数据方式的细节而变得杂乱不堪。 组件变得难以理解、难以测试,并且这些数据访问逻辑无法被复用,也无法标准化。

这就是为什么最佳实践中要求把数据展现逻辑从数据访问逻辑中拆分出去,也就是说把数据访问逻辑包装进一个单独的服务中, 并且在组件中把数据访问逻辑委托给这个服务。就算是这么简单的应用也要如此。


HttpClient

在全局注册 Angular 的 HttpClient 提供商:把 HttpClientModule 添加到应用模块(@NgModule)的 imports 数组中。

import { Injectable } from 'angular/core';
import { HttpClient } from 'angular/common/http'

@Injectable({
    providedIn: 'root'
})
export class CartService {
    constructor(private http: HttpClient) {}
    getShippingPrices() {
        return this.http.get('/assets/shipping.json');
    }
}

 

你可能感兴趣的:(angular)