您好,我正在嘗試從組件(HeaderComponent)調用另一個組件(ProductComponent)的方法。爲此我使用了一項服務。我創建了一個服務ProductService,它是這些組件中的一個共享服務。但我不更新視圖時,變量值在服務中更改請幫助。這裏是代碼無法通過服務更新組件角色的angular4視圖
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();
}
}
我在頁面加載時得到的最終輸出是初始的,但當調用方法 newProudutsData()時,它應該更改爲完成調用。
------ --------編輯
產物組分在頭組件中定義,通過該調用prodcut組件時路線
{
path: 'products/:id',
component: ProductsComponent
},
被調用。
顯示./products.component.html代碼 – alexKhymenko
和./products.component.html – alexKhymenko