两个组件如何在角度2中相互交谈

时间:2018-06-22 04:35:14

标签: angular typescript

我创建了两个组件: 1. create-articles:用于创建文章。 2.列出文章:用于列出所有文章。

父组件是家庭组件

import { Component, OnInit } from '@angular/core';


@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']

})
export class HomeComponent implements OnInit {
  constructor() { 
    
  }

  ngOnInit() {
  }

}
<div class="container">
    <div class="row">
        <div class="col-md-4">
            <articles-form></articles-form>
        </div>
        <div class="col-md-4">
            <articles></articles>
        </div>

    </div>
</div>

无论何时创建文章,我都希望刷新文章列表组件。

import { Component, OnInit } from '@angular/core';
import { ArticlesService } from '../../services/articles.service';
import { Article } from '../../models/article.model';
import { IArticles } from '../../interfaces/IArticles';
import { Observable } from 'rxjs';

@Component({
  selector: 'articles',
  templateUrl: './articles.component.html',
  styleUrls: ['./articles.component.css'],
  providers:[ArticlesService]
})
export class ArticlesComponent implements OnInit {

	articles: IArticles[];
	message:string;
	errorMessage:string;
	constructor(private as:ArticlesService) { }
	ngOnInit():void {
	  	this.fetchArticles();
	}
  
	fetchArticles(): void {
       	this.as.getArticles()
      	.subscribe( articles => {
            this.articles = articles
            console.log(this.articles);
        },
	    error => this.errorMessage = <any>error);    
  	};


}
<button class="btn btn-primary" (click)="fetchArticles()">
	Reload Data
</button>
<div class="table table-responsive">
	<table class="table table-bordered">
		<thead>
			<tr>
				<th>#</th>
				<th>Title</th>
			</tr>
		</thead>
		<tbody>
			<tr *ngFor="let article of articles;let i=index">
				<td>
					{{i+1}}
				</td>
				<td>
					{{article.articles.title}}
				</td>
			</tr>
		</tbody>
	</table>
</div>

import { Component, OnInit } from '@angular/core';
import { ArticlesService } from '../../services/articles.service';
import { Article } from '../../models/article.model';
import { IArticles } from '../../interfaces/IArticles';
import { Observable } from 'rxjs';
import { ArticlesComponent } from '../articles/articles.component';
import { EventEmitter, Input, Output } from '@angular/core';

@Component({
  selector: 'articles-form',
  templateUrl: './articles-form.component.html',
  styleUrls: ['./articles-form.component.css'],
  providers:[ArticlesService]
})
export class ArticlesFormComponent implements OnInit {
  books: IArticles[];
    article:IArticles=new Article(1,"Let Us C","Rahul Shaw","http://google.com");
  message:string;
  errorMessage:string;
  articles:IArticles[];
    constructor(private as:ArticlesService) { }

        ngOnInit():void {}

      onSubmit(data:IArticles) : void{
          var articles=this.as.createArticles(data)
          .subscribe( book => {
              this.message = "submitted"; 

          },
          error => this.errorMessage = <any>error);
      };

}
<div class="panel panel-primary">
    <div class="panel-body">
        <h1>Article Posting</h1>
        <form (ngSubmit)="onSubmit(article)">
            <div class="form-group">
              <label for="title">Title</label>
              <input type="text" class="form-control" id="title" required [(ngModel)]="article.title" name="title">
            </div>
            <div class="form-group">
              <label for="author">Author</label>
              <input type="text" class="form-control" id="author" required [(ngModel)]="article.author" name="author">
            </div>
            <div class="form-group">
              <label for="url">URL</label>
              <input type="text" class="form-control" id="url" [(ngModel)]="article.url" name="url">
            </div>
            <button type="submit" class="btn btn-default">      Submit
            </button>
            {{ name }}
        </form>
    </div>
</div>

无论何时创建文章,我都希望刷新文章列表组件。

3 个答案:

答案 0 :(得分:0)

可能的答案:-

Homecomponent.html(父级)

<create-article  [data]="createarticleData"></create-article>
<list-article [data]="listarticleData"></list-article>

Homecomponent.ts(父母)

createarticleData = "{"key":"value"}"
listarticleData= "{"key":"value"}"

create-article.component.ts

@Input data;

list-article.component.ts

@Input data;

用于调用函数:-

使用类型选择器

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}
@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild(ChildCmp) child:ChildCmp;
  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

带有字符串选择器

@Component({
  selector: 'child-cmp',
  template: '<p>child</p>'
})
class ChildCmp {
  doSomething() {}
}
@Component({
  selector: 'some-cmp',
  template: '<child-cmp #child></child-cmp>',
  directives: [ChildCmp]
})
class SomeCmp {
  @ViewChild('child') child:ChildCmp;
  ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

答案 1 :(得分:0)

有很多方法可以为猫皮。

您有3个组成部分:

  1. HomeComponent-具有子组件ArticlesFormComponent和ArticlesComponent
  2. ArticlesFormComponent-一个具有用于创建新Articles的表单的组件。
  3. ArticlesComponent-获取和列出所有Articles的组件。

这个想法是,您已经在获取ArticlesComponent的文章列表,并且可能将其存储在articlesArray之类的数组中,因此当您从ArticlesFormComponent创建新文章时,您将触发http请求,如果它返回成功响应,则可以将该文章添加到已经存在的articlesArray中,并且该文章将在ArticlesComponent中自动受到影响。

您已经有一个处理HTTP请求的ArticlesService,但是由于您的ArticlesService是在组件级别提供的,因此它具有不同的实例。最好在模块级别提供ArticlesService,以便您的应用程序具有单个实例。

@NgModule({
    ...
    providers:[
         ...,
         ArticlesService
    ]
})
export class AppModule { }

答案 2 :(得分:0)

您可以通过不同的方式与组件进行通信。

创建一项服务,以通过主题从子级向父级发送事件,以便您可以在应用程序中的任何位置订阅数据,并且该数据将自动更新

查看下面的示例代码段

<div class="container">
    <div class="row">
        <div class="col-md-4">
            <app-articles-form></app-articles-form>
        </div>
        <div class="col-md-4">
            <app-articles></app-articles>
        </div>

    </div>
</div>

检查示例:https://stackblitz.com/edit/angular-jncwsq