Naveen Singh
Naveen Singh

Reputation: 405

Can not update view on angular4 by component intraction through service

Hello I am trying to call method of another component(ProductComponent) from a component(HeaderComponent). for this i used a service. I created a service ProductService which is a shared service amoung these components. but I doesnt update the view when the variable value is changed in service please help. here is the code

productservice.service.ts

  import { Injectable, ChangeDetectorRef } from '@angular/core';
  import { Observable } from 'rxjs';
  import { Subject }    from 'rxjs/Subject';
  @Injectable()
  export class ProductServiceService {

    contentSource = new Subject();
    str = 'initial';
    content$ = this.contentSource.asObservable();
    constructor(private cdRef:ChangeDetectorRef) { }
    setData(str){
      this.str = str;
      console.log(str);
      this.cdRef.detectChanges();
    }
    getData(){
      return this.str;
    }

  }

header.component.ts

    @Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css'],
  providers: [ProductsComponent, ProductServiceService],
  changeDetection: ChangeDetectionStrategy.Default
})
export class HeaderComponent implements OnInit{

 constructor(public dialog: MdDialog,private _http: Http,  private cdRef:ChangeDetectorRef, private sharedService: ProductServiceService) 
 {
}    
ngOnInit() {
}
    newProudutsData(slug: string){
    this.sharedService.contentSource.next("echo");
    this.sharedService.setData('Done Calling');
    this.cdRef.detectChanges();
    }
}

product.component.ts

@Component({
    selector: 'app-products',
    templateUrl: './products.component.html',
    styleUrls: ['./products.component.css'],
    changeDetection: ChangeDetectionStrategy.Default,
    providers: [ProductServiceService],
})
export class ProductsComponent implements OnDestroy {
    slug='';
    subscription: Subscription;
    testdata = 'abcd';
    constructor(private _http: Http, private sharedService: ProductServiceService) 
    {
            this.testdata = sharedService.getData();
            console.log("received222");
    }
    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

the final output I am getting when the page loads is initial but when the method newProudutsData() is called it should be changed to Done Calling.

------ edited --------

product component is defined in header component by which calls prodcut component when route

{
            path: 'products/:id',
            component: ProductsComponent
 },

is called.

Upvotes: 2

Views: 76

Answers (1)

alexKhymenko
alexKhymenko

Reputation: 5598

The components have their own services and they are not connected. You should extract service to the module. When you specify service to the component you make it local only to that component meaning you have 2 different instances of service instead of one and they dont share data with each other. I recommned using augury in chrome deb tools to see the dependency injection

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

}

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

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [ProductsComponent , HeaderComponent  ]
  providers: [
     ProductServiceService
  ]
})
export class YourModule {}

Use behaviorSubject instead of subject

    contentSource = new BehaviorSubject('');

Subject doesn't save previous value BehaviorSubject does. And if source emit something but You were not subscribe at that time you will loose this value.

created Plunker

Upvotes: 1

Related Questions