更改子组件变量时更新父组件

时间:2017-01-13 07:26:37

标签: angular angular2-components

例如,我有一个名为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));
    }
}

如您所见,我有一个名为homeChanged的@Output变量,并在子组件初始化时发出totalQuantity。我需要在我的父组件中显示它如果仅用户已登录,因为这是导航栏上 Cart 唯一一次显示。

这是我的父组件。

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吗?

2 个答案:

答案 0 :(得分:3)

您可以使用主题,如下所示:

在你的父母:

  AppComponent.returned.subscribe(res => {
     console.log('change happened!');
     console.log(res) // you have your passed value here
  });

并在您的父构造函数中订阅了child中的更改,如下所示:

AppComponent.returned.next('test'); // pass whatever you need

在你的子组件中,你需要父级更新添加这个,并作为参数你想要的,这里我们只传递一个字符串。

    if(isset($_POST['id'])) {
        if(is_numeric($_POST['id'])) {
            $change = pg_query($db, "SELECT * FROM azubi3 WHERE id = ".$_POST['id']."");
            echo $change;
            if($auto == "") {
                $auto = "false";
            }
            else { $auto = "true"; }
            $change = pg_query($db, "UPDATE azubi3 SET vorname = '".$_POST['prename']."', nachname = '".$_POST['name']."', auto = ".$auto.", auto_id = ".$_POST['auto_id'].", schuh_id = ".$_POST['schuh_id']." WHERE id = ".$_POST['id']."");
        }
        else { echo "ID muss eine Zahl sein!"; }

    }

编辑:输出仅适用于您的子组件不在不同路径后面的情况。因此,在您的情况下,您不能使用输出。

答案 1 :(得分:0)

以下是如何从子级更新父组件。

        @Component({
          selector: 'child-selector',
          template: 'child.component.html'
        })
        export class ChildComponent {  
          @output() notify: EventEmitter<string> = new EventEmitter<string>();

          onClick() {
            this.notify.emit('Click from nested component');
          }
        }




        /* parent.conponent.html */
        <div>  
          <h1>I'm a container component</h1>
          <child-selector (notify)='onNotify($event)></child-selector>
        </div>  




        @Component({
          selector: 'parent-selector',
          template: 'parent.component.html',
          directives: [ChildComponent]
        })
        export class ParentComponent {  
          onNotify(message:string):void {
            alert(message);
          }
        }