-1

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

控制器.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 。

4

3 回答 3

0

也许这个?

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;
    }
}
于 2017-04-25T12:14:28.707 回答
0

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

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

然后问题就解决了。希望这有助于进一步的开发人员。

于 2020-10-27T19:38:53.493 回答
0

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

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

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

于 2020-10-29T06:38:27.740 回答