Skip to content

Instantly share code, notes, and snippets.

@imtiaz-emu
Created October 26, 2016 10:58
Show Gist options
  • Save imtiaz-emu/47aff0f752cb4680822716c62c091630 to your computer and use it in GitHub Desktop.
Save imtiaz-emu/47aff0f752cb4680822716c62c091630 to your computer and use it in GitHub Desktop.
Angular2 subject not subscribing in the parent component
Folder sturcture:
- Datapanel
- datapanel.component.ts
- datapanel.html
- datapanel.module.ts
- DataConnector
- dataconnector.component.ts
- database-information.service.ts
// parent component
export class DatapanelComponent implements OnInit, OnDestroy {
connectedDBNames = [];
private subscription: Subscription;
constructor(private _databaseInfo:DatabaseInformationService) { }
ngOnInit() {
this.subscription = this._databaseInfo.notifyObservable$.subscribe(
data => {
console.log(data);
this.connectedDBNames.push({'name': data, 'checked': false});
}
);
}
}
// common service
export class DatabaseInformationService {
private addDatabaseToDataPanel = new Subject<any>();
notifyObservable$ = this.addDatabaseToDataPanel.asObservable();
constructor(private http: Http) {
}
public addDataBaseToDataPanel(db_name){
this.addDatabaseToDataPanel.next(db_name);
console.log(db_name);
}
}
// child component
export class DatabaseConnectionComponent implements OnInit {
constructor(public databaseInfo: DatabaseInformationService) {}
saveDatabase(db_name: any, uri: any) {
this.databaseInfo.addDataBaseToDataPanel(db_name);
}
}
// datapanel.module.ts
@NgModule({
imports: [
CommonModule,AccordionModule,FormsModule
],
declarations: [DatapanelComponent, DatabaseConnectionComponent],
exports :[DatapanelComponent, DatabaseConnectionComponent],
providers:[DatabaseInformationService]
})
@ranakrunal9
Copy link

Its because of same name addDataBaseToDataPanel inside common service. Apply changes as below :

// common service
export class DatabaseInformationService {

  private addDatabaseToDataPanel = new Subject<any>();
  notifyObservable$ = this.addDatabaseToDataPanel.asObservable();

  constructor(private http: Http) {
  }

  public notifyDataBaseToDataPanel(db_name){
    this.addDatabaseToDataPanel.next(db_name);
    console.log(db_name);
  }
}

// child component
export class DatabaseConnectionComponent implements OnInit {

  constructor(public databaseInfo: DatabaseInformationService) {}

  saveDatabase(db_name: any, uri: any) {
    this.databaseInfo.notifyDataBaseToDataPanel(db_name);
  }

} 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment