GVKun编程网logo

Angular 2 - 在setTimeout中使用'this'(angular set get)

15

在本文中,我们将带你了解Angular2-在setTimeout中使用'this'在这篇文章中,我们将为您详细介绍Angular2-在setTimeout中使用'this'的方方面面,并解答angul

在本文中,我们将带你了解Angular 2 - 在setTimeout中使用'this'在这篇文章中,我们将为您详细介绍Angular 2 - 在setTimeout中使用'this'的方方面面,并解答angular set get常见的疑惑,同时我们还将给您一些技巧,以帮助您实现更有效的angulajs angularjs $timeout没有延迟参数的原因、Angular $ http:在'timeout'配置上设置一个承诺、Angular 2,异步测试和setTimeout、Angular HTTP 请求自定义 timeout 值的一种实现思路

本文目录一览:

Angular 2 - 在setTimeout中使用'this'(angular set get)

Angular 2 - 在setTimeout中使用'this'(angular set get)

我在课堂上有这样的功能

  showMessageSuccess(){    var that = this;    this.messageSuccess = true;    setTimeout(function(){      that.messageSuccess = false;    },3000);  }

我怎样才能重写这个,所以我不必在“那个”变量中存储对“这个”的引用?如果我在 setTimeout 中使用“this”,则 messageSuccess
bool 似乎不会更改/更新。

答案1

小编典典

您需要使用 箭头函数()=> ES6功能 thissetTimeout.

// var that = this;                        // no need of this linethis.messageSuccess = true;setTimeout(()=>{                           // <<<---using ()=> syntax    this.messageSuccess = false;}, 3000);

angulajs angularjs $timeout没有延迟参数的原因

angulajs angularjs $timeout没有延迟参数的原因

在几个脚本中我可以找到例如
$timeout(function () {
    $scope.my = 1;            
});

而不是简单

$scope.my = 1;

调用$ timeout没有延迟的目的是什么?

这是一个黑客。 :)但通常的目的是等待到$ digest周期结束,然后将$ scope.my设置为1.超时在所有手表完成后调用。

Angular $ http:在'timeout'配置上设置一个承诺

Angular $ http:在'timeout'配置上设置一个承诺

如何解决Angular $ http:在''timeout''配置上设置一个承诺?

此代码来自$httpBackend源代码:

if (timeout > 0) {
  var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (timeout && timeout.then) {
  timeout.then(timeoutRequest);
}

function timeoutRequest() {
  status = ABORTED;
  jsonpDone && jsonpDone();
  xhr && xhr.abort();
}

timeout.then(timeoutRequest) 表示在解决承诺(不拒绝)后,将调用timeoutRequest并中止xhr请求。

如果请求超时,则reject.status === 0( ),例如:

app.run(function($http, $q, $timeout){

  var deferred = $q.defer();

  $http.get(''/path/to/api'', { timeout: deferred.promise })
    .then(function(){
      // success handler
    },function(reject){
      // error handler            
      if(reject.status === 0) {
         // $http timeout
      } else {
         // response error status from server 
      }
    });

  $timeout(function() {
    deferred.resolve(); // this aborts the request!
  }, 1000);
});

解决方法

在Angular$httpdocs中,它提到您可以将“超时”配置设置为数字或承诺。

超时 – {number | Promise} –超时(以毫秒为单位),或承诺应在解决后中止请求。

但是我不确定如何使用诺言使这项工作成为现实。我如何设定数字和承诺?基本上,我希望能够知道http调用(承诺)是否由于“超时”或其他原因而出错。我需要能够分辨出差异。谢谢你的帮助
!!!

Angular 2,异步测试和setTimeout

Angular 2,异步测试和setTimeout

我有一个关于测试的问题.
我使用Angular 6,业力和茉莉.

我的测试是:

it(`my test`,async(() => {
    console.log('### start test');
    fixture.detectChanges();
    // call a method which has async code
    fixture.componentInstance.fakeTimeout();
    console.log('isstable',fixture.isstable());
    fixture.whenStable().then(() => {
        // here I must check smth only when all async operations are completed
        console.log('### end test');
    });
}));

我试图以不同的方式实现fakeTimeout方法,即:

public fakeTimeout() {
    new Promise((resolve,reject) => {
        setTimeout(() => {
            console.log('>>>>>> COMPONENT TIMEOUT!!!');
            resolve(true);
        },2000);
    }).then(() => {});
}

要么

public fakeTimeout() {
    setTimeout(() => {
        console.log('>>>>>> COMPONENT TIMEOUT!!!');
    },2000);
}

在这两种情况下,我都有以下日志:

### start test
isstable true
### end test
>>>>>> COMPONENT TIMEOUT!!!

但是,根据官方文档,whenStable promise只会解析所有异步操作,并且日志必须是:

### start test
isstable true
>>>>>> COMPONENT TIMEOUT!!!
### end test

我做错了什么?如果必须等待所有异步操作完成到我的组件中,我应该如何正确编写异步测试?

解决方法

不确定,为什么fixture.whenStable()不会自己等待延迟(setTimeout).

但它可以正常使用Promise或Observable返回

但你可以解决它的方式:

方法1:您可以使用tick()手动等待使用fakeAync

it(`my test`,fakeAsync(() => {
    console.log('### start test');
    fixture.detectChanges();
    // call a method which has async code
    fixture.componentInstance.fakeTimeout();
    tick(2100); // just more than the delay mentioned inside the component.
    console.log('isstable',fixture.isstable());
    fixture.whenStable().then(() => {
        // here I must check smth only when all async operations are completed
        console.log('### end test');
    });
}));

方法2:在spec文件中有自己的setTimeout并使用done()完成测试

it(`my test`,((done) => {
        console.log('### start test');
        fixture.detectChanges();
        // call a method which has async code
        fixture.componentInstance.fakeTimeout();
        setTimeout(()=> {
          console.log('isstable',fixture.isstable());
          console.log('### end test');
          done();
        },2100)
}));

Angular HTTP 请求自定义 timeout 值的一种实现思路

Angular HTTP 请求自定义 timeout 值的一种实现思路

本文介绍 Angular HTTP 请求 timeout 的一种实现思路。的

如果不扩展 HttpClientModule 类,拦截器与相应请求进行通信的唯一预期方式是参数和标头对象。

由于超时值是标量(Scalar)的,它可以安全地作为自定义标头提供给拦截器,可以通过 RxJS 超时运算符(timeout Operator)来决定是默认超时还是特定超时。

代码片段如下:

import { Inject, Injectable, InjectionToken } from ''@angular/core'';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from ''@angular/common/http'';
import { Observable } from ''rxjs'';
import { timeout } from ''rxjs/operators'';

export const DEFAULT_TIMEOUT = new InjectionToken<number>(''defaultTimeout'');

@Injectable()
export class TimeoutInterceptor implements HttpInterceptor {
  constructor(@Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number) {
  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const timeoutValue = req.headers.get(''timeout'') || this.defaultTimeout;
    const timeoutValueNumeric = Number(timeoutValue);

    return next.handle(req).pipe(timeout(timeoutValueNumeric));
  }
}

上面代码里,timeout 是 rxjs 提供的一个 Operator.

DEFAULT_TIMEOUT 这个 injection token, 以及 HTTP Interceptor 的提供方式,定义在 App Module 中:

providers: [
  [{ provide: HTTP_INTERCEPTORS, useClass: TimeoutInterceptor, multi: true }],
  [{ provide: DEFAULT_TIMEOUT, useValue: 30000 }]
],

然后,我们就可以使用下面的代码来调用 HTTPClient,使用自定义的 timeout 值了:

http.get(''/your/url/here'', { headers: new HttpHeaders({ timeout: `${20000}` }) });

另外,Angular 的 proxy 设置里也允许定义 timeout 值:

{
  "/api": {
    "target": "http://localhost:3000",
    "secure": false,
    "timeout": 360000
  }
}

关于 rxjs 的 timeout Operator 的输入参数,首先需要知道的是,如果没有给配置提供 with 属性,当满足超时条件时,这个操作符会发出一个 TimeoutError。 相反,如果配置了 with 属性,Angular 将使用 with 提供的工厂函数,并将开发人员的订阅切换到其结果。 超时条件由 first 和 each 中的设置提供。

第一个属性可以是特定时间的日期、相对于订阅点的时间段的数字,也可以被跳过。 此属性仅用于检查来自源的第一个值到达的超时条件。 来自源的所有后续值的时间将根据每个提供的时间段进行检查(如果已提供)。

关于Angular 2 - 在setTimeout中使用'this'angular set get的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于angulajs angularjs $timeout没有延迟参数的原因、Angular $ http:在'timeout'配置上设置一个承诺、Angular 2,异步测试和setTimeout、Angular HTTP 请求自定义 timeout 值的一种实现思路的相关知识,请在本站寻找。

本文标签: