您好我正在尝试从组件(HeaderComponent)调用另一个组件(ProductComponent)的方法。为此,我使用了一项服务。我创建了一个ServiceService服务,它是这些组件的共享服务。但我在服务中更改变量值时不更新视图请帮助。这是代码
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。
------编辑--------
产品组件在标头组件中定义,在路由
时通过该组件调用prodcut组件{
path: 'products/:id',
component: ProductsComponent
},
被召唤。
答案 0 :(得分:1)
组件有自己的服务,但没有连接。您应该将服务提取到模块。当您为组件指定服务时,只将其设置为本地组件意味着您有2个不同的服务实例而不是1个,并且它们不会彼此共享数据。我建议在chrome deb工具中使用augury来查看依赖注入
@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 {}
使用behaviorSubject代替主题
contentSource = new BehaviorSubject('');
主题不保存BehaviorSubject以前的值。 如果源发出了一些东西但你当时没有订阅,那么你将失去这个值。