我的目标是获取我的购物车项目的总数量,并将其显示在我的主要组件内的导航栏上的我的购物车链接上。Angular 2 - 在组件之间使用共享服务传递数据
这里是我的购物车服务
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class CartService {
totalQuantity: Number = 0;
constructor(private _http: Http) { };
getCartItems(userId) {
let headers = new Headers({ 'Authorization': 'JWT ' + localStorage.getItem('currentUserToken') });
let options = new RequestOptions({ headers: headers });
return this._http.get('http://localhost:3000/cart/getitem/' + userId, options)
.map((response: Response) => {
this.totalQuantity = response.json().totalQuantity;
return response.json();
})
.catch(this._handlerError)
}
updateCartItem(item){
console.log(item);
let headers = new Headers({ 'Authorization': 'JWT ' + localStorage.getItem('currentUserToken') });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:3000/cart/updateitem/', item, options)
.map((response: Response) => {
this.totalQuantity = response.json().totalQuantity;
return response.json();
})
.catch(this._handlerError)
}
removeCartItem(item){
let headers = new Headers({ 'Authorization': 'JWT ' + localStorage.getItem('currentUserToken') });
let options = new RequestOptions({ headers: headers });
return this._http.post('http://localhost:3000/cart/deleteitem/', item, options)
.map((response: Response) => {
this.totalQuantity = response.json().totalQuantity;
return response.json();
})
.catch(this._handlerError)
}
_handlerError(err: any) {
console.log(err);
// throw err;
return Observable.throw(err);
}
}
我做了名为totalQuantity
公共变量和执行的购物车服务的功能之一后充满价值。此totalQuantity
变量由app组件访问。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { loginStatusChanged } from './auth.guard';
import { CartService } from './cart';
import { UserService } from './user';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
title = 'app works!';
loginStatus: boolean;
constructor(private _cartService: CartService, private _userService: UserService, private _router: Router){}
totalQuantity = this._cartService.totalQuantity;
onLogout(){
this._userService.logout();
loginStatusChanged.next(false);
this._router.navigate(['/login']);
}
ngOnInit(){
this.onLogout();
loginStatusChanged.subscribe(status => this.loginStatus = status);
}
}
我觉得这里的问题是:1。 如果用户不执行从cartService一个函数,则totalQuantity
变量将永远不会有一个值。 2.我怎样才能得到ONLY IF用户登录的的totalQuantity
值。
谁能帮我解决这个问题吗?我卡住了。
你能建议我应该在哪里更新AppComponent中的totalQuantity方法吗?因为我很确定它不会去onInit,因为一旦AppComponent初始化后没有用户登录。 –