-
Notifications
You must be signed in to change notification settings - Fork 24.7k
/
promise_pipe.ts
88 lines (78 loc) 路 2.17 KB
/
promise_pipe.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import {Promise, PromiseWrapper} from 'angular2/src/facade/async';
import {isBlank, isPresent, isPromise, CONST} from 'angular2/src/facade/lang';
import {Pipe, WrappedValue} from './pipe';
import {ChangeDetectorRef} from '../change_detector_ref';
/**
* Implements async bindings to Promise.
*
* # Example
*
* In this example we bind the description promise to the DOM.
* The async pipe will convert a promise to the value with which it is resolved. It will also
* request a change detection check when the promise is resolved.
*
* ```
* @Component({
* selector: "task-cmp",
* changeDetection: ON_PUSH
* })
* @View({
* template: "Task Description {{ description | async }}"
* })
* class Task {
* description:Promise<string>;
* }
*
* ```
*
* @exportedAs angular2/pipes
*/
export class PromisePipe implements Pipe {
_latestValue: Object = null;
_latestReturnedValue: Object = null;
_sourcePromise: Promise<any>;
constructor(public _ref: ChangeDetectorRef) {}
supports(promise): boolean { return isPromise(promise); }
onDestroy(): void {
if (isPresent(this._sourcePromise)) {
this._latestValue = null;
this._latestReturnedValue = null;
this._sourcePromise = null;
}
}
transform(promise: Promise<any>): any {
if (isBlank(this._sourcePromise)) {
this._sourcePromise = promise;
promise.then((val) => {
if (this._sourcePromise === promise) {
this._updateLatestValue(val);
}
});
return null;
}
if (promise !== this._sourcePromise) {
this._sourcePromise = null;
return this.transform(promise);
}
if (this._latestValue === this._latestReturnedValue) {
return this._latestReturnedValue;
} else {
this._latestReturnedValue = this._latestValue;
return WrappedValue.wrap(this._latestValue);
}
}
_updateLatestValue(value: Object) {
this._latestValue = value;
this._ref.requestCheck();
}
}
/**
* Provides a factory for [PromisePipe].
*
* @exportedAs angular2/pipes
*/
@CONST()
export class PromisePipeFactory {
supports(promise): boolean { return isPromise(promise); }
create(cdRef): Pipe { return new PromisePipe(cdRef); }
}