最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在Angular 8中子与父组件之间的通信

运维笔记admin10浏览0评论

在Angular 8中子与父组件之间的通信

在Angular 8中子与父组件之间的通信

我正在尝试与我的上级控制器通信,已在其子组件中添加了新项目。我知道为此,我必须使用@Output和事件发射器,并且正在使用它们,但它似乎没有用。还有另一种方法可以做到这一点吗?

这是我的孩子组成部分

import { Component, OnInit, Input, ViewChild, ElementRef, Output, EventEmitter } from '@angular/core';
import { Namespace } from '../../../models/Namespace';
import { Schema } from '../../../models/Schema'
import { ApiNamespaceService } from '../../../Services/api-namespace.service'
import { Router } from '@angular/router';

@Component({
  selector: 'add-namespace',
  templateUrl: './add-namespaceponent.html',
  styleUrls: ['./add-namespaceponent.css']
})
export class AddNamespaceComponent implements OnInit {

newNamespace = new Namespace();
selectedSchema = new Schema();
schemas: Schema[];
@Input() namespaces: Namespace[];
@ViewChild('alert', { static: true }) alert: ElementRef;
@ViewChild("nameInput", { static: false }) nameInputRef: ElementRef;
success = false;
@Output() public namespaceCreated = new EventEmitter<Namespace[]>();

constructor(private namespaceService: ApiNamespaceService, private router: Router) {
    this.schemas = [{ Name: this.selectedSchema.Name, SchemaData: this.selectedSchema.SchemaData, Id: this.selectedSchema.Id }];
}

ngOnInit() {
    this.getSchemas();
}

getSchemas(): void {
    this.namespaceService.getAllSchemas().subscribe(schemas => this.schemas = schemas);
}

createNamespace(): void {
    if (this.nameInputRef.nativeElement.value != '') {
        this.newNamespace.SchemaId = this.selectedSchema.Id;
        this.newNamespace.Roles = [];
        this.namespaceService
            .createNamespace(this.newNamespace)
            .subscribe(nmsp => this.namespaces.push(nmsp));
        this.success = true;
    }
    this.namespaceCreated.emit(this.namespaces);
    this.router.navigateByUrl('main-view/namespaces');
}

createName(): void {
    if (this.nameInputRef.nativeElement.value === '') {
        this.newNamespace.Name = 'Null';
    }
}

closeAlert() {
    this.success = false;
}

这里是我在父HTML中调用函数的位置

<div *ngIf="shouldOpen" class="col-6">
    <add-namespace [namespaces]="namespaces" (namespaceCreated)="showNewNamespace($event)"></add-namespace>
</div>

这是父组件ts

import { Component, OnInit, ViewChild } from '@angular/core';
import { ApiNamespaceService } from '../../Services/api-namespace.service'

import { Namespace } from '../../models/Namespace'
import { EditNamespaceComponent } from './edit-namespace/edit-namespaceponent';
import { Router } from '@angular/router';

@Component({
  selector: 'namespaces',
  templateUrl: './namespacesponent.html',
  styleUrls: ['./namespacesponent.css']
})
export class NamespacesComponent implements OnInit {

namespaces: Namespace[];
selectedNamespace: Namespace;
shouldOpen = false;
query: string;
filteredNamespaces: Namespace[];

constructor(private namespaceService: ApiNamespaceService, private router: Router) { }

ngOnInit() {
    this.getNamespaces();
}

getNamespaces(): void {
    this.namespaceService.getAllNamespaces().subscribe(namespaces => {
        this.namespaces = namespaces;
        this.filteredNamespaces = namespaces;
        this.search();
    });
}

openAddNamespace() {
    this.shouldOpen = true;
}

openNamespace(namespace: Namespace) {
    this.shouldOpen = false;
    this.selectedNamespace = namespace;
    this.router.navigateByUrl('main-view/namespaces/' + this.selectedNamespace.Id);
}

search() {
    if (!this.query || !this.query.trim()) {
        this.filteredNamespaces = this.namespaces;
        return;
    }

    this.filteredNamespaces = this.namespaces.filter(namespace => namespace.Name.toLowerCase()
        .includes(this.query.toLowerCase().trim()));
}

showNewNamespace($event) {
    this.namespaces = $event;
}    
回答如下:

您可以使用Subject来做到这一点。这是我的博客的link供您参考

import { Injectable } from "@angular/core";
import { Subject } from "rxjs";

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    constructor() {}

    sendMessage(message: any) {
        this.subject.next(message);
    }

    getData() {
        return this.subject.asObservable();
    }
}

我在这里定义了2种方法。第一种使用next()将消息发送到下一个订阅者的方法。因此,在您的组件中,您只需要像这样简单地订阅即可获取数据

private subscription$: Subscription;

public ngOnInit(): void {
  this.subscription$ = this.messageervice
            .getData()
            .subscribe(data => { console.log(data); })
}

public ngOnDestroy(): void {
    this.subscription$.unsubscribe();
}
发布评论

评论列表(0)

  1. 暂无评论