下面的解决方案不适用于角度路由器。当我调用一个方法时,它正在成功调用一个服务方法,但父内容ieEmployer Component somethingChangedHandler()没有被执行。
@Component({
selector: 'w2',
templateUrl: '../../html/views/w2old.html',
providers:[ListReloadService]
})
export class W2Component implements OnInit {
constructor(private _httpService:HttpService,
private _router : Router,
private _activatedRoute :ActivatedRoute,
private _listReloadService:ListReloadService){
}
submitW2()
{
this._listReloadService.emitEvent(false);
//calling parent somethingChangedHandler()
}
}
**MySevice**
@Injectable()
export class ListReloadService {
@Output()
public somethingChanged: EventEmitter<boolean>;
constructor(private _http: Http){
this.somethingChanged = new EventEmitter();
}
public emitEvent(val: boolean){
console.log("hello");
this.somethingChanged.emit(val);
}
}
**parent component**
@Component({
selector: 'employerhome',
templateUrl: '../../html/views/employerhome.html',
providers:[ListReloadService]
})
export class EmployerHomeComponent
{
constructor(private httpService:HttpService, private listReloadService : ListReloadService){
this.listReloadService.somethingChanged
.subscribe(data=>this.somethingChangedHandler(data));
}
private somethingChangedHandler(someVal)
{
console.log("hello hi");
}
}
答案 0 :(得分:0)
创建服务,例如:
import {Injectable} from '@angular/core';
@Injectable()
export class HiService {
sayHi() {
console.log("Hi!")
}
}
注入AppComponent:
...
providers: [HiService]
...
在您的组件中使用它:
constructor(private hi: HiService) {
console.log("constructor")
}
ngOnInit(): void {
this.hi.sayHi()
}