【问题标题】:Angular 2 - Setting Timeout in a ServiceAngular 2 - 在服务中设置超时
【发布时间】:2017-10-21 03:23:00
【问题描述】:

我想在我的 Angular 2 项目的服务中创建延迟以进行测试。更具体地说,我想要

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 中吗?预先感谢您的帮助!

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      您可以简单地使用delay operator:

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

      【讨论】:

      • @Pengyy 不会改变任何东西。如果你把它放在第一位,则接收到 http 响应,然后在 1 秒后发出,然后映射到 JSON。如果你把它放在最后,就会收到 http 响应,映射到 JSON,然后在 1 秒后发出。在这两种情况下,都会在 1 秒后发出 JSON。
      • delay() 找不到。我应该导入什么??
      • 延迟操作符,和其他操作符一样:import 'rxjs/add/operator/delay';
      • 非常感谢您的帮助!
      【解决方案3】:

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

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

      注意:指定的时间以毫秒

      为单位

      【讨论】:

      • timeout() 找不到。我应该导入什么??
      • import 'rxjs/add/operator/timeout';
      • 我相信标题在“setTimeout”中的意思是“超时”,正如另一个答案中所建议的那样。
      • 不会在 200 秒后取消服务调用
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-27
      • 2013-05-18
      • 1970-01-01
      • 2013-01-14
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多