Search code examples
javascriptangulartypescriptangular2-servicesangular2-cookie

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

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.


Solution

  • It was my mistake to add CookieService in component providers which initiate a new instance of service which was causing the issue.

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

    CookieService should only be imported into AppComponent(root) to make a single instance available to other components.