Cookie undefined in service | cookie value exist i

2019-09-20 08:01发布

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
    }
}

I don't understand this behavior. The cookie exist when i access in controller directly but is undefined when i access through service.

Is there any way to access cookie through services?

using https://github.com/salemdar/angular2-cookie with angular universal.

1条回答
家丑人穷心不美
2楼-- · 2019-09-20 08:07

Maybe this?

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

and then

api-service

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;
    }
}
查看更多
登录 后发表回答