在我的項目反映我有兩個組成部分傳遞數據從一個組件到另一個鑑於
component1.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
<div *ngFor="let emp of employee" (click)="onSelect(emp.name)">
Id: {{emp.id}} <br />
Name: {{emp.name}}
</div>
這裏的onclick emp.name傳遞給服務通過onselect()
我需要此val UE被傳遞到第二部件
component2.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-component2',
templateUrl: './component2.component.html',
styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
private selectedName: string;
constructor() { }
ngOnInit() {
}
}
HTML
<p>
selected name is: {{selectedName}}
</p>
服務代碼是:
import { Injectable } from '@angular/core';
@Injectable()
export class MyserviceService {
private myValue;
constructor() { }
setValue(val) {
this.myValue = val;
}
getValue() {
return this.myValue;
}
}
我需要在COMPONENT2 HTML代碼來顯示名稱作爲變量selectedName。
我已添加 import'BehaviorSubject} from'rxjs'; private myValue = new BehaviorSubject(); public myValue $ = this.myValue.asObservable(); 它顯示錯誤,如 提供的參數不匹配任何調用目標的簽名。) –
什麼行會導致此錯誤? –
private myValue = new BehaviorSubject(); –