正在尝试为我的应用程序实现暂停装饰器,但我在另一个问题之后遇到了问题



我有一个服务文件:

export class MockDataService {
data:[] = [];
getAll(): Observable<any[]> { return of(this.data); }
}

我想基本上为我的模拟创建一个延迟,所以我想在所有函数周围包装一个@pause()装饰器:

export async function pause() {
await new Promise( res => setTimeout(res, 1500) );
}

因此,从本质上讲,所有端点都将有 1.5 秒的暂停。 我将其添加到 getAll:

@pause()
getAll() {}

但它给了我一个来自我的智力的错误。Unable to resolve signature of method decorator when called as an expression. Cannot invoke an expression whose type lacks a call signature. Type 'Promise<void>' has no compatible call signatures.

我试图弄清楚我将如何实现这一目标。 我的函数签名有误吗? 我最终将在函数中利用 Http 调用,所以我认为我有正确的函数定义

您收到错误是因为方法修饰器必须具有以下签名:

declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;

它无法返回Promise<void>.它必须返回TypedPropertyDescriptor<T>或必须无效。由于您正在处理Observable<>因此您需要使用rxjs/operators中的delay运算符:

export function observablePause(
target: Object,
propertyName: string,
propertyDesciptor: PropertyDescriptor): PropertyDescriptor {
const method = propertyDesciptor.value;
propertyDesciptor.value = function (...args: any[]) {
// invoke decorated method and get its return value
let result = <Observable<any>>method.apply(this, args);
// adding delay
result = result.pipe(delay(1500));
// return the result of invoking the method
return result;
}
return propertyDesciptor;
};
...
@observablePause
getAll(): Observable<any[]> { return of(this.data); }

这会让你等待,但我认为你可能对可观察到的响应有其他问题。

@Injectable({
providedIn: 'root'
})
export class MockDataService {
data: [] = [];
@delay()
downloadData() {
return this.data;
}
getAll(): Observable<any[]> {
return of(this.downloadData());
}
constructor() {
}
}
export function delay(): MethodDecorator {
return function(target: Function, key: string, descriptor: any) {
const originalMethod = descriptor.value;
descriptor.value =  async function(...args: any[]) {
console.log('Entering Wait!');
await new Promise(res => setTimeout(res, 1500));
console.log('Completed Wait!');
return originalMethod.apply(this, args);
};
return descriptor;
};
}

相关内容

最新更新