服务中未定义的 Cookie | cookie 值存在于组件 | angular

Cookie undefined in service | cookie value exist in component | angular

api.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/operator/retry';

import { CacheService  } from './cache.service';
import { AuthService } from '../services/auth.service';
import { CookieService } from 'angular2-cookie/core';

@Injectable()
export class ApiService {
    constructor(
        public _http: Http, 
        private _auth: AuthService,
        private _cookie: CookieService,
        @Inject('isBrowser') public isBrowser: boolean
        ) {}

        get(){
          console.log(this._cookie.get('Token'));//undefined
        }
    }

controller.component.ts

import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { ApiService } from './api.service';
import { ReviewComponent } from '../shared/+review/review.component';
import { CookieService } from 'angular2-cookie/core';
// import { ModelService } from '../shared/model/model.service';

@Component({
    selector: 'mall',
    templateUrl: './mall.component.html',
    styleUrls:['./mall.component.css'],
    providers: [ ApiService, CookieService ]
})
export class MallComponent implements OnInit {

    constructor(private _api: ApiService, private route: ActivatedRoute, private _cookie: CookieService) {}

    ngOnInit(){
        this._cookie.get('Token');// Token => value
        this._api.get(); //Token => undefined
    }
}

我不明白这种行为。当我直接在控制器中访问时 cookie 存在,但当我通过服务访问时未定义。

有没有办法通过服务访问cookie?

使用 https://github.com/salemdar/angular2-cookie 和 angular 通用。

也许是这个?

ngOnInit(){
  this._cookie.put('Token', WHATEVER_TOKEN_IS);// Token => value
  console.log(this._api.get('Token')); //Token => undefined
}

然后

api-服务

export class ApiService {
  constructor(
    readonly _http: Http, 
    private _auth: AuthService,
    private _cookie: CookieService,
    @Inject('isBrowser') public isBrowser: boolean
    ) {}

    get() {
      const token = this._cookie.get('Token');
      console.log(token);
      return token;
    }
}

这可能晚了,但我遇到了同样的问题。 我没有将基本路径定义为“/”。所以发生的事情是cookie被设置为我所在的默认路径。 例如。我在现场com/auth/ Cookie 将保存在路径“/auth” 如果我像

这样保存一个 cookie
this.cookieService.set('token', token, null, "/");

那么问题就解决了。 希望这对进一步的开发者有帮助。

我在组件提供程序中添加 CookieService 是我的错误,它启动了导致问题的新服务实例。

@Component({
    selector: 'mall',
    templateUrl: './mall.component.html',
    styleUrls:['./mall.component.css'],
    providers: [ ApiService, CookieService ] //<--- here
})

CookieService 只应导入到 AppComponent(root) 中以创建单个实例可用于其他组件。