如何从角度应用程序调用REST方法POST / wallet / {name} / setDefault?

时间:2018-05-07 17:11:57

标签: angular rest post hyperledger-composer

这是我第一次使用Angular。我有一个在Hyperledger Composer生成的REST服务器上运行的angular 4应用程序。我正在尝试对应用程序进行一些更改,例如添加一些REST调用。

我想调用REST方法: POST / wallet / {name} / setDefault

The definition of the method

但我不知道如何传递参数名称。

这是用于POST CALL的文件的内容:

home.component.html

<div class="container">
    <button (click)="setDefaultWalletCard('hatcher1');" type="submit" class="btn btn-success" value="Refresh Page" onClick="setTimeout(window.location.reload.bind(window.location), 2000);" data-dismiss="modal">Confirm</button>
</div>

home.component.ts

import { Component } from '@angular/core';
import { DataService } from './home.service';
@Component({
    selector: 'app-home',
    templateUrl: './home.component.html',
    styleUrls: ['./home.component.css'],
  providers: [DataService]
})
export class HomeComponent {
constructor (private dataService: DataService){
};
    public setDefaultWalletCard(card: string) {
     return this.dataService.setDefaultCard(card);
    }
}

home.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
@Injectable()
export class DataService{
    private resolveSuffix: string = '?resolve=true';
    private actionUrl: string;
    private headers: Headers;

    constructor(private http: Http) {
        this.actionUrl = '/api/';
        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

  public setDefaultCard(cardName){
   var data = new FormData();
   data.append("", "");
   return this.http.post('localhost:3000/api/wallet/'+cardName+'/setDefault', data, {withCredentials: true});
 }
}

我得到的错误是:

状态响应:URL为0:null

你能帮帮我吗?感谢

1 个答案:

答案 0 :(得分:0)

就我而言,像http.posthttp.get之类的有针对性的http调用一样,返回所谓的可观察对象。您可以定义observable在完成或遇到错误后必须执行的操作,但它不会自动执行任何操作。它的激活方式是通过订阅,将其从转换为

因此,为了实际召唤你的帖子,你必须在某处订阅,因为它充当了实际事件的触发器。如果您不需要对响应做出反应,请将subscribe函数保留为空。以下是home.component.ts文件中呼叫的示例。

setDefaultWalletCard(card: string) {
     this.dataService.setDefaultCard(card).subscribe(()=>{
        // nothing to do here
        // ... or maybe just perform your page reload here after the call is finished
     });
     // also I don't think you have to return the observable to the form
}

查看this question,这与您的非常相似。答案非常简洁:

  

这意味着Observable表示的函数仅使用subscribe方法激活。

还有一个指向该主题的链接,可以为您提供比我在此处提供的更多信息。