के साथ किसी सेवा से घटकों में परिवर्तनीय परिवर्तनों को अद्यतन करना मेरे ऐप में नाम सेवा है जिसका नाम है।कोणीय 2
ऐप, नवबार और द कॉन्टेंट के दो बच्चे घटक हैं जो इस सेवा का संदर्भ देते हैं। जब भी सेवा में नाम बदलता है, मैं चाहता हूं कि यह दोनों अन्य घटकों में अपडेट हो। मैं यह कैसे कर सकता हूँ?
import {Component, Injectable} from 'angular2/core'
// Name Service
@Injectable()
class NameService {
name: any;
constructor() {
this.name = "Jack";
}
change(){
this.name = "Jane";
}
}
// The navbar
@Component({
selector: 'navbar',
template: '<div>This is the navbar, user name is {{name}}.</div>'
})
export class Navbar {
name: any;
constructor(nameService: NameService) {
this.name = nameService.name;
}
}
// The content area
@Component({
selector: 'thecontent',
template: '<div>This is the content area. Hello user {{name}}. <button (click)=changeMyName()>Change the name</button></div>'
})
export class TheContent {
name: any;
constructor(public nameService: NameService) {
this.name = nameService.name;
}
changeMyName() {
this.nameService.change();
console.log(this.nameService.name);
}
}
@Component({
selector: 'app',
providers: [NameService],
directives: [TheContent, Navbar],
template: '<navbar></navbar><thecontent></thecontent>'
})
export class App {
constructor(public nameService: NameService) {
}
}
इसके अलावा में घटना से सदस्यता समाप्त करने के लिए याद घटक घटक, घटक उदाहरण जारी नहीं किया जाएगा। सब्सक्राइब फ़ंक्शन द्वारा लौटाई गई ऑब्जेक्ट पर सदस्यता रद्द करने की आवश्यकता है। – Chandermani
@ कंधर्मनी क्या आप इस बारे में संकेत दे सकते हैं कि टीएस में यह कैसे किया जाता है? –
'सदस्यता लें = nameService.nameChange.subscribe ((मान) => {this.name = value;}); subscription.unsubscribe() '। मुझे इस मुद्दे का सामना करना पड़ा इसलिए अस्वीकरण। यदि सदस्यता को अन्य विधि से रद्द करना है, तो परिवर्तनीय वर्ग स्तर – Chandermani