从Angular 4中的另一个组件调用组件方法

时间:2017-11-02 03:47:01

标签: angular

我是Angular的新手,我有两个组件,app.componentadd.component。在app.component中,模板包含li's,可从数据库(服务)获取动态内容。现在在add.component,我想从app.component调用该方法,以便在用户通过{{{}中的表单成功添加数据后,li's内的ul内容将会更新1}}

app.component.ts

add.component

}

app.component.html

import { Component, OnInit } from '@angular/core';
import { AuthService } from './services/auth.service';

import { CheatService } from './services/cheat.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
 })
export class AppComponent implements OnInit {
  cheaterNames = [];
   constructor(public auth: AuthService, private cheatService: CheatService) 
  { }

ngOnInit() {
    this.getNames();
}
getNames() {// I want to call this method after the user submit the form in add.component
    this.cheatService.getNames().subscribe(
        res => {
            this.cheaterNames = res;
        },
        error => console.log(error)
    );
}
onAdded(ok) {
    if (ok === 'ok') {
        this.getNames();
        console.log('called');
    } else {
        console.log('not called');
    }
}

add.component.ts

<ul class="nav nav-pills flex-column" *ngFor="let option of cheaterNames">
    <li class="nav-item">
        <a [routerLink]="['/cheats',option]" class="nav-link" routerLinkActive="active">
            <i class="fa fa-user"></i> {{ option }}
        </a>
    </li>
</ul>

add.component.html

export class AddComponent implements OnInit {
isEditing = false;
public cheats = [];
public cheaterNames = [];
public selectedName = null;
addCheatForm: FormGroup;
title = new FormControl('', Validators.required);
code = new FormControl('', Validators.required);
description = new FormControl('', Validators.required);
name = new FormControl('', Validators.required);

@Output() onAdded = new EventEmitter();
constructor(private cheatService: CheatService, private formBuilder: FormBuilder, public toast: ToastComponent) {}

ngOnInit() {
    this.addCheatForm = this.formBuilder.group({
        title: this.title,
        code: this.code,
        description: this.description,
        name: this.name
    });
    //this.getNames();
}
addCheat() {
    this.cheatService.addCheat(this.addCheatForm.value).subscribe(
        res => {
            const newCheat = res.json();
            this.cheats.push(newCheat);
            this.addCheatForm.reset();
            this.onAdded.emit('ok');//here I want to call getNames() from app.component, 
            this.toast.setMessage('item added successfully.', 'success');
        },
        error => console.log(error)
    );
}

关于最简单方法的任何想法?我也听说过共享服务,但我仍感到困惑。

2 个答案:

答案 0 :(得分:1)

我认为您忘记在子组件上添加SELECT QID, [Text], [Value] FROM TableA

onAdded

答案 1 :(得分:0)

好的,我明白了

首先我创建了一个共享服务

>) { message.payload... }

然后我更新了我的app.component和add.component

import { Injectable, Inject } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class CommonService {
   private notify = new Subject<any>();
   /**
   * Observable string streams
   */
   notifyObservable$ = this.notify.asObservable();

    constructor() {}

    public notifyOther(data: any) {
       if (data) {
         this.notify.next(data);
       }
    }
}

add.component

import { Component, OnInit } from '@angular/core';
import { Subscription } from 'rxjs/Subscription';
import { AuthService } from './services/auth.service';

import { CheatService } from './services/cheat.service';
import { CommonService } from './shared/common/common.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  cheaterNames = [];
  private subscription: Subscription;
  constructor(public auth: AuthService,
    private cheatService: CheatService,
    private commonService: CommonService) { }

 ngOnInit() {
    this.getNames();
    this.subscription = this.commonService.notifyObservable$.subscribe((res) => {
        if (res.hasOwnProperty('option') && res.option === 'onSubmit') {
            console.log(res.value, 'called once');
            // perform your other action from here
            this.getNames();
        }
    });
}
getNames() {
    this.cheatService.getNames().subscribe(
        res => {
            this.cheaterNames = res;
        },
        error => console.log(error)
    );
 }
}