问题描述
api.service.ts
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
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 存在,但当我通过服务访问时未定义.
I don't understand this behavior. The cookie exist when i access in controller directly but is undefined when i access through service.
有没有办法通过服务访问cookie?
Is there any way to access cookie through services?
使用 https://github.com/salemdar/angular2-cookie 和 angular 通用.
using https://github.com/salemdar/angular2-cookie with angular universal.
推荐答案
在组件提供程序中添加 CookieService
是我的错误,该组件提供程序启动导致问题的新服务实例.
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 应仅导入到 AppComponent(root) 中,以使其他组件可以使用单个实例.
CookieService should only be imported into AppComponent(root) to make a single instance available to other components.
这篇关于服务中未定义 Cookie |cookie 值存在于组件中 |有角的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!