typescript - Angular 2 หลายคอมโพเนนต์พร้อมผู้สังเกตแบบส่วนตัว
ฉันมีแอปพลิเคชัน Angular 2 ซึ่งในคอมโพเนนต์ที่เรียกว่า ComponentB จะแสดงคอมโพเนนต์ ComponentA หลายครั้ง ComponentA นี้มี Service ที่เกี่ยวข้องซึ่งฉันใช้ในการเรียกข้อมูล และเมื่อการเรียกเหล่านี้ได้รับคำตอบ Service จะส่งอ็อบเจกต์ observable ที่ต้องถูกจับโดย ComponentA สิ่งที่ฉันต้องการคือ ComponentA หมายเลข 1 ต้องจับสตรีมของ Service ที่ถูกสร้างขึ้นใน ComponentA หมายเลข 1 เท่านั้น เพื่อให้ ComponentA หมายเลข 2 ในการเปลี่ยนแปลงเดียวกันยังคงเหมือนเดิม
ลองทำตัวอย่าง
คอมโพเนนต์ HTMLB
<componentA *ngFor="let el of list"></componentA>
ส่วนประกอบตัวพิมพ์B
@Component({
selector:"componentB",
templateUrl:"./componentB"
styleUrls:["./componentB.css"]
})
export class ComponentB implements OnInit{
ngOnInit(){}
private list:string[]=['','']
}
คอมโพเนนต์ HTMLA
<div>{{variable}}</div>
<button (click)="changeVariable()"></button>
ไทป์สคริปต์
@Component({
selector:"componentA",
templateUrl:"./componentA"
styleUrls:["./componentA.css"]
})
export class ComponentA implements OnInit{
constructor(private sA:serviceA){
sA.callObservable.subscribe(
arg0=>this.variable=arg0
)
}
private variable:any;
changeVariable(){
this.sA.call()
}
}
บริการ A
@Injectable()
export class ServiceA {
private item=new Subject<string>();
callObservable=this.item.asObservable()
call(){
this.getForCall().subscribe(
arg0=>item.next(arg0)
)
}
getForCall():Observable<string>{
.... the call and the conversion to json ...
}
}
มีอะไรผิดพลาดในโค้ดนี้หรือเปล่า? ฉันคิดว่ามันน่าจะเป็นวิธีแก้ปัญหาด้วยการกำหนดค่าแบบส่วนตัวในตัวสร้างของคอมโพเนนต์ A แต่ดูเหมือนว่าจะไม่ทำงานและทุกอย่างเปลี่ยนไป
อัปเดต
เพื่อความชัดเจนมากขึ้น ในตัวอย่างผมต้องการว่า: ถ้าผมคลิกปุ่มในองค์ประกอบแรกของคอมโพเนนต์ A ภายในคอมโพเนนต์ B ผมไม่ต้องการให้ค่าของ 'ตัวแปร' ถูกเปลี่ยนในคอมโพเนนต์ A ที่สองภายในคอมโพเนนต์ B
คำตอบ #1
ลองตั้งค่า provider ของ ServiceA สำหรับแต่ละ ComponentA เพื่อที่จะได้มีหลายอินสแตนซ์ของ ServiceA (มันไม่ใช่ singleton) ที่ให้บริการแต่ละ ComponentA แยกกัน ลบ serviceA ออกจากอาเรย์ providers ในโมดูลของคุณ
@Component({
selector:"componentA",
templateUrl:"./componentA",
styleUrls:["./componentA.css"],
providers: [ serviceA ]
})
export class ComponentA implements OnInit{
constructor(private sA:serviceA){
// ...
}
}
