例如,我有一個名爲totalQuantity的變量來自服務。更改子組件變量時的父組件變量
我有一個初始化變量ONLY如果用戶。
已經登錄這是子組件的子組件。
import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import { CartService } from '../cart';
@Component({
selector: 'landing',
templateUrl: './landing.component.html'
})
export class LandingComponent implements OnInit{
@Output() homeChanged = new EventEmitter;
constructor(private _cartService: CartService){}
ngOnInit(){
this._cartService.getCartItems(localStorage.getItem('currentUserId'))
.subscribe((cart) => {
this.homeChanged.emit(this._cartService.totalQuantity);
console.log(this._cartService.totalQuantity);
},
err => console.log(err));
}
}
正如你所看到的,我有一個@Output變量稱爲homeChanged當子組件初始化會發出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){}
onLogout(){
this._userService.logout();
loginStatusChanged.next(false);
this._router.navigate(['/login']);
}
ngOnInit(){
this.onLogout();
loginStatusChanged.subscribe(status => this.loginStatus = status);
}
}
父組件的HTML,我會把totalQuantity
<ul class="navigation">
<li class="logo"><img src="assets/images/nav_logo.png"></li>
<li><a routerLink="/home" routerLinkActive="active">Home</a></li>
<li><a routerLink="/mainproducts" routerLinkActive="active">Products</a></li>
<li *ngIf="loginStatus"><a href="http://localhost:3000">Designer</a></li>
<li *ngIf="loginStatus"><a routerLink="/cart" routerLinkActive="active">Cart({{totalQuantity}})</a></li>
<li *ngIf="!loginStatus"><a routerLink="/login" routerLinkActive="active">Login</a></li>
<li *ngIf="loginStatus" class="dropdown"><a (click)="onLogout()">Logout</a></li>
</ul>
<router-outlet></router-outlet>
誰能幫我上我的車旁邊導航欄顯示totalQuantity?
你在哪裏設置你的屬性我沒有看到它在AppComponent中的設置? –
你在哪裏使用着陸組件?你需要像' ' –
none。我正在使用路由器插座進行導航。有什麼方法可以更新購物車嗎? –