![](/img/trans.png)
[英]Unable to pass data between Angular 2 components using a shared service
[英]Angular 2 - Using shared service pass data between components
我的目的是獲取購物車項目的總數,並將其顯示在主要組件內導航欄上的購物車鏈接上。
這是我的購物車服務
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
變量由應用程序組件訪問。
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. 僅在用戶登錄后才能獲取totalQuantity
的值。
誰能幫我解決這個問題? 我被卡住了。
我看不到您的app.module.ts,但是請確保您需要在提供程序中添加CartService。
- 如果用戶未從cartService執行函數,則totalQuantity變量將永遠沒有值。
不,因為您寫道您的totalQuantity初始化為0。
- 僅當用戶登錄時,如何才能獲得totalQuantity的值。
在您的sharedService中,您可以使用一個函數,該函數將通過簽入(如果用戶已登錄)來獲取totalQuantity。
getTotalQuantity() {
let isLoggedIn: boolean = methodThatCheckIfLoggedIn();
if (isLoggedIn)
return this.totalQuantity;
return null;
}
標題“在組件之間使用共享服務傳遞數據”表明存在設計問題。 如果希望在組件之間傳遞數據,則可能應該在組件之間傳遞數據( @Input
和@Output
)。
具有某些服務方法填充的共享變量( totalQuantity
)會引入時間耦合。 該值僅在之前已執行其他操作時才正確。 我建議使totalQuantity
成為一種獲取其自身值的方法可能會更好。 如果您擔心性能成本並願意犧牲一致性,則可以在方法中緩存值。
最后,如果您不想執行任何操作,則只需從AppComponent
構造函數中調用一種更新totalQuantity
的方法,然后更新totalQuantity
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.