Angular 2 - 设置服务中的超时

时间:2017-05-21 11:40:46

标签: angular

我想在Angular 2项目的Service中创建一个延迟用于测试目的。更具体地说,我想要

的召唤
this.myIatreioService.getIatreia()

延迟1秒。我的服务如下:

@Injectable()
export class IatreioService {
   private headers = new Headers();

   constructor(private http: Http) {
       let token = localStorage.getItem('token');
       if (token) {
         this.headers = new Headers({ 'Authorization': 'Bearer ' + token });
       }
   }

   getIatreia(): Observable<Iatreio[]> {
       return this.http
                  .get('http://localhost:3000/iatreia', { headers: this.headers })
                  .map(response => response.json() as Iatreio[]);
   }

} // end of Service

我试图实现setTimeout函数,但它没有工作:

getIatreia(): Observable<Iatreio[]> {
   setTimeout(() => {   
      return this.http
                 .get('http://localhost:3000/iatreia', { headers: this.headers })
                 .map(response => response.json() as Iatreio[]);
   }, 1000);
}

我的问题有解决方案吗?如果没有,我可以将setTimeout()放在Component或Server中吗?预先感谢您的帮助!

3 个答案:

答案 0 :(得分:4)

您只需使用delay operator

即可
return this.http
           .get('http://localhost:3000/iatreia', { headers: this.headers })
           .map(response => response.json() as Iatreio[])
           .delay(1000);

答案 1 :(得分:0)

当您使用Observable时,请使用下面的超时运算符

return this.http
                 .get('http://localhost:3000/iatreia', { headers: this.headers })
                 .map(response => response.json() as Iatreio[])
                 .timeout(200, 'Timeout has occurred.');

注意:指定的时间是毫秒

答案 2 :(得分:0)

使用httpClient,您可以执行以下操作:

myService() {
        return this.httpClient.get('http://.to.co/')
            .timeout(200, timeout)
            .map((data) => {
                return data;
            })
            .catch((error: Response) => {
                return (error);
            });
    }