无法从另一个组件调用组件的Angle 2服务 [英] Unable to call angular 2 service of component from another component
问题描述
我必须有2个组件LeftPanelComponent和RightPanelComponent.我为我的实现引用了此代码
I have to 2 component LeftPanelComponent and RightPanelComponent. I referred this code for my implementation
我在两个组件之间创建了一个共享服务,以从LeftPanelComponent调用RightPanelComponent的abc()函数.
I created one shared service between two component to call abc() function of RightPanelComponent from LeftPanelComponent.
我正在将ListDialogComponent中的值读取到LeftPanelComponent中,并传递给abc()函数.
I'm reading value from ListDialogComponent into LeftPanelComponent and passing to abc() function.
abc()函数正在从LeftPanelComponent成功调用.
abc() function of RightPanelComponent is calling successfully from LeftPanelComponent.
但是,当我在abc()函数中调用saveCustomData()angular 2服务时,就会出现以下错误.
But when I'm calling saveCustomData() angular 2 service in abc() function then I'm getting following error.
EXCEPTION: Error in ./ListDialogComponent class ListDialogComponent - inline template:29:6 caused by: Cannot read property 'saveCustomData' of undefined
LeftPanelComponent.ts
LeftPanelComponent.ts
import { Component, OnInit } from '@angular/core';
import {LeftpanelService} from "../leftpanel.service"
import {Leftpanel} from "../leftpanel";
import {MdDialog} from "@angular/material";
import {MdDialogRef} from "@angular/material";
import {ListDialogComponent} from "../list-dialog/list-dialog.component";
import {SharedService} from '../shared-service/shared-service.component';
@Component({
selector: 'app-leftpanel',
templateUrl: './leftpanel.component.html',
styleUrls: ['./leftpanel.component.css']
})
export class LeftpanelComponent implements OnInit {
dialogRef: MdDialogRef<any>;
leftpanels:Leftpanel[];
constructor(public dialog: MdDialog,private service:LeftpanelService, private sharedService: SharedService) {
}
ngOnInit() {
this.service.getLeftpanels().subscribe(lst =>this.leftpanels=lst);
}
transferDataSuccess($event) {
this.receivedData.push($event.dragData);
this.openDialog();
}
openDialog() {
this.dialogRef.afterClosed().subscribe(result => {
console.log('result: ' + result);
this.dialogRef = null;
this.sharedService.componentOneFn(sessionStorage.getItem("value"));
});
}
}
ListDialog.Component.html
ListDialog.Component.html
<form class="form-group" >
<select name="itemid" #selectedCategory class="selectOption">
<option value="">Choose Item</option>
<option *ngFor="let Item of Items" value="{{Item.id}}" >{{Item.name}}</option>
</select>
<p></p>
<button type="button" (click)="dialogRef.close('yes',getValueFromSelect(selectedCategory.value))" class="btn">Submit</button>
<button type="button" (click)="dialogRef.close('no')" class="btn">Cancel</button>
</form>
ListDialogComponent.ts
ListDialogComponent.ts
import { Component,OnInit} from '@angular/core';
import {MdDialogRef} from "@angular/material";
import {Item} from '../item';
import {GetListService} from '../get-list.service';
@Component({
selector: 'app-list-dialog',
templateUrl: './list-dialog.component.html',
styleUrls: ['./list-dialog.component.css']
})
export class ListDialogComponent implements OnInit {
Items : Item[];
serverItemID : string;
constructor(public dialogRef: MdDialogRef<ListDialogComponent>,private service:GetListService) { }
ngOnInit() {
this.service.getItemList(this.oauthTokenService.getHeaders()).subscribe(lst =>this.Item=slst);
}
getValueFromSelect(value){
sessionStorage.setItem('value',value);
}
}
RightPanelComponent.ts
RightPanelComponent.ts
import {SaveCustomItem} from '../save-custom-item';
import {SaveCustomService} from '../save-custom.service';
import {SharedService} from '../shared-service/shared-service.component';
@Component({
selector: 'app-rightpanel',
templateUrl: './rightpanel.component.html',
styleUrls: ['./rightpanel.component.css']
})
export class RightpanelComponent implements OnInit {
componentData = [];
componentData2 = [];
saveCustomItems:saveCustomItem[];
constructor(public dialog: MdDialog, private service:SaveCustomService, private sharedService: SharedService) {
this.sharedService.componentOneFn = this.abc;
}
abc(value) {
if(value == "MyValue") {
this.service.saveCustomData(value).subscribe(lst =>this.saveCustomItems=lst);
}
}
}
SharedService.ts
SharedService.ts
import {Injectable} from '@angular/core';
@Injectable()
export class SharedService {
componentOneFn: Function;
constructor() { }
}
SaveCustomService.ts
SaveCustomService.ts
import { Injectable } from '@angular/core';
import {Http, Response, Headers} from "@angular/http";
import {Observable} from "rxjs/Rx";
import 'rxjs/Rx';
import {AppSettings} from './appsettings';
import {SaveCustomItem} from './save-custom--item';
@Injectable()
export class SaveCustomService {
constructor(private http:Http) { }
saveCustomData(value):Observable<SaveCustomItem[]> {
let response = this.http.get(`${AppSettings.BACK_ENDPOINT}/ajax/save-custom-data?value=`+value);
let saveCustomItems = response.map(mapSaveCustomData);
return saveCustomItems;
}
}
function mapSaveCustomData(response:Response):SaveCustomItem[] {
return response.json().results.map(toSaveCustomData);
}
function toSaveCustomData(r:any):SaveCustomItem {
let saveCustomeItem = <SaveCustomItem>({
id:r.server,
title:r.title
});
return saveCustomeItem;
}
推荐答案
在 SaveCustomService
中,您要在类clousure括号}
之外声明您的方法.
In SaveCustomService
you are declaring your methods outside the class clousure bracket }
.
应该是这样的:
@Injectable()
export class SaveCustomService {
constructor(private http: Http) {
}
saveCustomData(value): Observable<SaveCustomItem[]> {
let response = this.http.get(`${AppSettings.BACK_ENDPOINT}/ajax/save-custom-data?value=` + value);
let saveCustomItems = response.map(mapSaveCustomData);
return saveCustomItems;
}
mapSaveCustomData(response: Response): SaveCustomItem[] {
return response.json().results.map(toSaveCustomData);
}
toSaveCustomData(r: any): SaveCustomItem {
let saveCustomeItem = <SaveCustomItem>({
id: r.server,
title: r.title
});
return saveCustomeItem;
}
}
无法读取未定义的属性'saveCustomData'
Cannot read property 'saveCustomData' of undefined
表示未定义 this.service.saveCustomData
中的 this.service
.
因此,我认为您应该检查并确保导入中的 ../shared-service/shared-service.component
是正确的路径.
So, I think that you should check and be certain that ../shared-service/shared-service.component
in your import is the correct path.
还记得在模块的提供者
中添加 SharedService
:
Also remember to add SharedService
in your module's providers
:
@NgModule({
providers: [SharedService]
只是个小费.您可以为概念性块或范围创建1个服务.并使用它在共享相同概念块或范围的组件之间传递数据.
Just a tip. You can create 1 service for a conceptual block or scope. And use it to pass data between components that share the same conceptual block or scope.
在文档中: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service ,您将了解如何使用它1服务将数据从任务组件传递到宇航员组件,它们都属于一个概念块:宇航员执行任务".
In the documentation: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service , you see how it is used 1 service to pass data from Mission Component to Astronaut Component, they both belong to one conceptual block: 'Astronaut performing mission'.
同一件事将应用于这些更常见的概念范围:用户",订单",付款"等.
Same thing would be applied to these more common conceptual scopes: 'Users', 'Orders', 'Payments', and so on.
您无需创建服务A即可调用服务B的方法.直接调用服务B.
这篇关于无法从另一个组件调用组件的Angle 2服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!