私はオブジェクト指向プログラミングを初めて学びました。これは、熟練したOOプログラマにとっては簡単なコンセプトであるはずですが、確かに苦労しています。下図のように私のAngular2アプリであるクラスのメソッドの値をTypescriptの別のクラスのメソッドに渡すには?
は私がHTTPServiceのクラスを持っている:
http.service.ts
@Injectable()
export class HttpService {
constructor(private http: Http) { }
addLeaf(parentId, label, name){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('http://localhost:8000/addleaf/',
{'parentId':parentId,'label':label, 'name':name},
{ headers: headers })
.map(res => res).subscribe();
}
私は以下のように別のクラスの中から、このメソッドを呼び出すようにしてみてください。
リーフ.ts
import { HttpService } from './http.service';
export class Leaf{
name: string;
...
http: Http; // very unsure about these two lines
private httpService: HttpService = new HttpService(this.http)
constructor(input){
this.name = input.name;
...
add(){
//what should go here?
this.httpservice.addLeaf(this.id, this.label, this.name);
//error -> cannot read property 'post' of undefined
}
thisを読むと、HttpServiceクラスのインスタンスを作成しようとしましたが、投稿機能が存在しないというエラーが表示されます。コンストラクタにhttpServiceを置くことも無駄です。
私はこのように私のhtmlでのメソッド呼び出し:
(click)="leaf.add()"
EDIT:示すように、私はleaf.tsを変更し、leaf.component.tsを追加peeskilletの答え@以下:
葉.TS
export class Leaf{
name: string;
...
constructor(input){
this.name = input.name;
...
add(){
//what should go here?
}
}
leaf.component.ts
@Component({
providers: [HttpService],
})
export class LeafComponent {
leaf: Leaf;
constructor(private httpService: HttpService) {
this.httpService.addLeaf(this.leaf.id, this.leaf.type, this.leaf.name)
}
}
サービスは、私がのparamsの代わりに事前定義された文字列を書く場合は正常に動作しますが、それでも私はこれにクリックされた葉のパラメータを渡すことができるかどうかはわかりません。
サービスの説明をありがとう、しかし私はまだそのサービスのメソッドにパラメータを渡す方法については不明です。私の場合のリーフは、いくつかのプロパティ(名前、ラベルなど)を持つオブジェクトで、これらの値をhttpサービスに渡したいと思います。 – Arash
私はサービスが葉のメンバーでなければならないと思います。私はあなたがコンポーネントのリーフとサービスのメンバーの両方を持っている必要があると思う。リクエストを送信するときは、リーフからプロパティを取得し、それをサービスメソッドに渡します。 –
はい、私はリーフからサービスを削除して新しいコンポーネントを作りました。そこにサービスを追加しました。パラメータの場所にあらかじめ定義された文字列を置くと、サービスは正常に動作しますが、そのサービスへのリーフオブジェクトをクリックしたときのパラメータ。私は精巧に質問を編集します。 – Arash