阅读有关可观察性的文章,在问题末尾找到了代码。
我无法理解以下几行->
return this._subscribe({
onNext: onNext,
onError: onError || (() => {}),
onCompleted: onCompleted || (() => {})
});
1)我以前从未见过这种语法,这到底是什么?
使用typeof表示其为对象,但对我来说,它看起来像是函数内的对象,这没有任何意义。
2)由于我不懂代码,所以玩耍发现如果我返回
return {
onNext: onNext,
onError: onError || (() => {}),
onCompleted: onCompleted || (() => {})
}
代码将不会到达第二点(在“返回新的Observable((obs)”)之后),直到第二点(在下面查找-> // PointTwo)
我认为第二个问题的答案与第一个问题有关。
export class Observable<T> {
/** Internal implementation detail */
private _subscribe: any;
/**
* @constructor
* @param {Function} subscribe is the function that is called when the
* observable is subscribed to. This function is given a subscriber/observer
* which provides the three methods on the Observer interface:
* onNext, onError, and onCompleted
*/
constructor(subscribe: any) {
if (subscribe) {
this._subscribe = subscribe;
};
}
// public api for registering an observer
subscribe(onNext: any, onError?: any, onCompleted?: any) {
if (typeof onNext === 'function') {
return this._subscribe({
onNext: onNext,
onError: onError || (() => {}),
onCompleted: onCompleted || (() => {})
});
} else {
throw new Error("Please provide a function")
}
}
static of(...args): Observable {
return new Observable((obs) => {
//pointTwo
args.forEach(val => {
console.log("3")
obs.onNext(val)
});
obs.onCompleted();
return {
unsubscribe: () => {
// just make sure none of the original subscriber's methods are never called.
obs = {
onNext: () => {},
onError: () => {},
onCompleted: () => {}
};
}
};
});
}
}
Observable.of(42).subscribe((num) => {console.log("number is -> " + num)})
答案 0 :(得分:2)
这不是特定于TS的。他们要做的就是直接在函数调用中定义对象文字,而不是在调用函数之前:
const functionThatTakesAnObject = (obj) => {
console.log(obj);
};
const object = { prop1: true, somethingElse: '1' };
// pass in an object bound to a variable
functionThatTakesAnObject(object);
// define an object literal directly in the invocation
functionThatTakesAnObject({ prop1: true, somethingElse: '1' });