2017-04-12 10 views
0

2コンポーネントのLeftPanelComponentとRightPanelComponentが必要です。私が参照しましたthis code for my implementation別のコンポーネントからコンポーネントのangle 2サービスを呼び出せません

LeftPanelComponentからRightPanelComponentのabc()関数を呼び出す2つのコンポーネント間で1つの共有サービスを作成しました。

ListDialogComponentからLeftPanelComponentに値を読み込み、abc()関数に渡しています。

RightPanelComponentのabc()関数がLeftPanelComponentから正常に呼び出されています。

しかし、abc()関数でsaveCustomData()angular 2のサービスを呼び出すと、次のエラーが発生します。

EXCEPTION: Error in ./ListDialogComponent class ListDialogComponent - inline template:29:6 caused by: Cannot read property 'saveCustomData' of undefined 

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

<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

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

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

import {Injectable} from '@angular/core'; 
@Injectable() 
export class SharedService { 

componentOneFn: Function; 

constructor() { } 
} 

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; 
} 
+0

ダブルチェックすることを '../共有サービス/共有service.component' – SrAxi

+0

'list-dialog.component.html'コードを追加できますか? – SrAxi

+0

SaveCustomServiceのコードを追加します。 – Faly

答えて

2

SaveCustomServiceでは、クラスclousureブラケット}外あなたの方法を宣言しています。

は、このようにする必要があります:

@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' this.service.saveCustomDatathis.serviceが未定義であることを意味します。

したがって、インポートの../shared-service/shared-service.componentが正しいパスであることを確認してください。

@NgModule({ 
    providers: [SharedService] 

EDIT2:

ただ、先端

また、モジュールのprovidersSharedServiceを追加することを忘れないでください。 概念的なブロックまたはスコープに対して1つのサービスを作成できます。また、同じ概念ブロックまたはスコープを共有するコンポーネント間でデータを渡すためにも使用します。

ドキュメント:https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-serviceでは、Missionコンポーネントから宇宙飛行士コンポーネントにデータを渡すために1サービスがどのように使用されているかがわかります。それらは両方とも、1つの概念ブロック「宇宙飛行士の実行ミッション」に属します。

「ユーザー」、「注文」、「支払い」など、より一般的な概念スコープにも同じことが適用されます。

あなたは、私は私の問題を解決し、直接B.

+0

ありがとうございました。しかし、あなたの答えは機能しません。 –

+0

@AnilJagtap私の答えで編集をチェックしてください。エラーの原因が他にあるかどうかを探し続けるつもりです。 – SrAxi

+0

私は既にプロバイダでsharedServiceを保持しています。まだ問題があります。私は何をする必要がありますか? –

0

にサービスを提供するサービスB.コールのメソッドを呼び出すために、サービスAを作成する必要はありません。 SharedService、LeftPanelComponent、およびRightPanelComponentでいくつかの変更を行いました。

SharedService.ts

import {Injectable} from '@angular/core'; 
@Injectable() 
export class SharedService { 

// Observable string streams 
componentMethodCalled$ = this.componentMethodCallSource.asObservable(); 

// Service message commands 
callRightPanelComponentMethod() { 
this.componentMethodCallSource.next(); 
} 
} 

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 { 
saveCustomItems:saveCustomItem[]; 

constructor(public dialog: MdDialog, private service:SaveCustomService, 
    private sharedService: SharedService) { 
    this.sharedService.componentMethodCalled$.subscribe(
    () => { 
    this.abc(); 
    } 
); 
} 
abc(value) { 
    if(value == "MyValue") { 
    this.service.saveCustomData(value).subscribe(lst =>this.saveCustomItems=lst); 
} 
} 
} 

RightPanelComponent.ts

openDialog() { 
this.dialogRef.afterClosed().subscribe(result => { 
    console.log('result: ' + result); 
    this.dialogRef = null; 
    this.sharedService.callRightPanelComponentMethod(); 
}); 
} 
関連する問題