Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Maybe this?

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

and then

api-service

exportclassApiService {
  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;
    }
}

Solution 2:

This might be late, but I went through the same problem. I was not defining the base path as "/". So what was happening is that the cookie was being set for the default path where I was. Eg. I was at site.com/auth/ Cookie would get saved at path "/auth" If I save a cookie like

this.cookieService.set('token', token, null, "/");

then problem is solved. Hope this helps further devs.

Solution 3:

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.

Post a Comment for "Cookie Undefined In Service | Cookie Value Exist In Component | Angular"