Angular 将数据从一个组件传递到另一个组件,并在视图中反映

Angular 将数据从一个组件传递到另一个组件,并在视图中反映,angular,typescript,visual-studio-code,Angular,Typescript,Visual Studio Code,在我的项目中,我有两个组件 组件1.ts import { Component, OnInit } from '@angular/core'; import { MyserviceService } from '../myservice.service'; @Component({ selector: 'app-component1', templateUrl: './component1.component.html', styleUrls: ['./component1.component

在我的项目中,我有两个组件

组件1.ts

import { Component, OnInit } from '@angular/core';
import { MyserviceService } from '../myservice.service';

@Component({
selector: 'app-component1',
templateUrl: './component1.component.html',
styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {

constructor(private Service: MyserviceService) { }
 employee = [
 { id: '001', name: 'michael' },
 { id: '002', name: 'john' },
 { id: '003', name: 'james' },
 { id: '004', name: 'joe' },
 ];
 ngOnInit() {
 }

 onSelect(name) {
  alert(name);
  this.Service.setValue(name);
 }
 }
html

html


我需要在component2 html代码中将名称显示为变量selectedName。

最好使用observable主动通知订阅者有关值更改的信息:

@Injectable()
export class MyserviceService {
  private myValue = new BehaviorSubject<String>(null);
  public myValue$ = this.myValue.asObservable();
}

Angular文档介绍了如何使用@Input绑定 [

在组件1 html格式中,id和名称在方括号内,替换div标记为组件2选择器标记的名称

<app-component2 *ngFor="let emp of employee" (click)="onSelect(emp.name)"
  [hero]="hero"
  [master]="master">
</app-component2>
在组件2中的html

<p>
selected name is: {{Name}}
</p>

所选名称为:{{name}


我已从“rxjs”添加了导入{BehaviorSubject};私有myValue=new BehaviorSubject();公共myValue$=this.myValue.asObservable();它显示错误,提供的参数与调用目标的任何签名都不匹配。)私有myValue=new BehaviorSubject();现在没有错误,但视图没有更新,是因为我遗漏了什么吗?。您是说
选定的名称是:{{selectedName}
,这是
Component2Component
s模板的一部分吗?是的,这部分是component2的html代码,当单击component1的div时,单击的名称应设置为“selectedName is:{{selectedName}}“我正在使用服务将此名称设置为component2。
import { Injectable } from '@angular/core';

@Injectable()
export class MyserviceService {
 private myValue;
  constructor() { }
   setValue(val) {
    this.myValue = val;

  }

  getValue() {
    return this.myValue;
 }
 }
@Injectable()
export class MyserviceService {
  private myValue = new BehaviorSubject<String>(null);
  public myValue$ = this.myValue.asObservable();
}
 export class Component2Component implements OnInit {
 private selectedName: string;
   constructor(service:MyserviceService) { 
     this.service.myValue$.subscribe(val => this.selectedName = val);
   }
 }
<app-component2 *ngFor="let emp of employee" (click)="onSelect(emp.name)"
  [hero]="hero"
  [master]="master">
</app-component2>
import { Component, Input } from '@angular/core';


export class Component2Component {
  @Input() Id: string;
  @Input() Name: string;
}
<p>
selected name is: {{Name}}
</p>