简体   繁体   English

尽管document.cookie包含值,但$ cookies.get()给出了未定义的值

[英]$cookies.get() gives undefined although document.cookie contains the value

In the following code, xsrfCookie is sometimes undefined. 在以下代码中, xsrfCookie 有时是未定义的。 I've measured it at about 20% of the calls. 我估计约有20%的来电。

This only seems to happen in MacOS Safari and on iOS in Safari en Chrome. 这似乎只发生在MacOS Safari和Safari en Chrome的iOS中。 I am using Angular 1.5.6. 我正在使用Angular 1.5.6。

 $http.get('some_url') .success(function() { var xsrfCookie = $cookies.get('XSRF-TOKEN'); }); 

Setting a breakpoint before or after xsrfCookie and logging document.cookie or even $cookies.get('XSRF-TOKEN') consistently shows the expected XSRF token. 在xsrfCookie之前或之后设置断点并记录document.cookie甚至$cookies.get('XSRF-TOKEN')始终显示预期的XSRF令牌。

I can only imagine this has something to do with the XSRF token from the GET being set asynchronously, in parallel to the success function, but I can't find anything in the angular.get() code that would suggest this. 我只能想象这与GET中的XSRF令牌有关,它与成功函数并行地异步设置,但是我在angular.get()代码中找不到任何暗示这一点的东西。

Is there anyone who has run into this issue? 有没有人遇到过这个问题?

So far I have solved this by wrapping the retrieval of the cookie in a timeout: 到目前为止,我已经通过在超时中包装对Cookie的检索来解决了这一问题:

$http.get('some_url')
  .success(function() {
    $timeout(function() {
      var xsrfCookie = $cookies.get('XSRF-TOKEN');
    }, 1);
  });

Unfortunately, I've not been able to find why this would be needed (expect that it might have something to do with the AngularJS 1.5 digest cycle) but I did found out some other things: 不幸的是,我无法找到为什么需要这样做(期望它可能与AngularJS 1.5摘要循环有关),但是我确实发现了其他一些东西:

  • The original problem only occurs in Safari on iOS and MacOS, and only some of the time. 最初的问题仅在部分时间出现在iOS和MacOS上的Safari中。 Depending on the environment (intranet, internet) but also varying from day to day, I had sometimes a 100% failure rate and it would sometimes be as low as 10%. 根据环境(企业内部网,互联网)的不同,但每天都有所不同,我的失败率有时是100%,有时甚至会低到10%。
  • If I log document.cookie as the first thing in the success callback, it is also empty (again only in Safari and only sometimes) 如果我将document.cookie为成功回调中的第一件事,则它也为空(同样仅在Safari中,有时也是如此)
  • It might be that $timeout is only triggered after the digest is finished and even $timeout without the milliseconds param would work 可能是$timeout仅在摘要完成后才触发,甚至没有毫秒参数的$timeout也可以工作
  • There are hooks like onInit that would only run after the digest cycle is complete, but this call is several service calls deep and I do not understand how this would be involved. onInit这样的钩子仅在摘要循环完成后才运行,但是此调用是深入的几个服务调用,我不知道这将如何涉及。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM