【发布时间】:2018-03-01 06:16:29
【问题描述】:
您好,我正在尝试从组件(HeaderComponent)调用另一个组件(ProductComponent)的方法。为此,我使用了一项服务。我创建了一个服务 ProductService,它是这些组件之间的共享服务。但是当变量值在服务中更改时我不会更新视图请帮助。这是代码
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() 应将其更改为 Done Calling。
-----已编辑--------
product组件定义在header组件中,路由时调用prodcut组件
{
path: 'products/:id',
component: ProductsComponent
},
被调用。
【问题讨论】:
-
显示 ./products.component.html 代码
-
和 ./products.component.html