如何发送POST Angular 2

时间:2017-06-07 03:25:55

标签: angular angular2-services

我正在研究Angular 2/4以便能够尽快使用该框架,但我对POST部分非常困惑,我使用Github API在我的存储库中发布“问题”但我仍然无法做到它...如果你能澄清这一点,我会非常感激,发送一个“问题”类型测试,以了解它在Angular 2/4中是如何工作的,因为我知道它必须以“JSON”格式发送才能工作但我不明白如何...使用github api:https://developer.github.com/v3/issues/#create-an-issue

我的代码:

github.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers, Response} from '@angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class GithubService {

  private username: string;
  private reponame: string;
  private client_id = '+++++++++++++++++++++++';
  private client_secret = '++++++++++++++++++++++++++++';

  constructor(private http: Http) {
    console.log('Github Service Ready...');
    this.username = 'anubis';
  }

  getGithubUser() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  getGithubRepository() {
    return this.http.get('http://api.github.com/users/' + this.username
      + '/repos'
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret )
      .map( res => res.json());
  }

  // to search another user and show his/her repositories
  SearchAgain(usernamenew: string) {
    this.username = usernamenew;
  }


  // I HAVE PROBLEMS IN THIS PART
  addIssue(forms) {
    this.reponame = 'LinioAngularProfileListMarcoAntonioVMontoyaCardenas';
    const headers = new Headers({'Content-Type': 'application/json'});

    return this.http.post('http://api.github.com/repos/ ' + this.username + ' / '
        + this.reponame + ' /issues?' + forms
      + '?client_id=' + this.client_id
      + '&client_secret=' + this.client_secret,
      {headers: headers}).map(res => res.json());
  }

}

issue.component.ts

import { Component, OnInit } from '@angular/core';
import { GithubService } from '../../Services/github.service';
import { ActivatedRoute, Params, Router } from '@angular/router';

@Component({
  selector: 'app-issue',
  templateUrl: './issue.component.html'
})
export class IssueComponent implements OnInit {

  user: any;
  repo: any[];
  username: string;

  constructor(private service: GithubService,
              private route: ActivatedRoute,
              private router: Router) { }

  ngOnInit() {
    this.user = false;

    this.route.params
      .subscribe(
        (params: Params) => {
          // this.id = +params['id'];
          // this.editMode = params['id'] != null;
          // this.initForm();
        }
      );
  }

  OnSearchUser() {
    // get user information
    this.service.getGithubUser().subscribe(userGit => {
      console.log(userGit);
      this.user = userGit;
    });

    // get user repositories
    this.service.getGithubRepository().subscribe(userRepo => {
      console.log(userRepo);
      this.repo = userRepo;
    });

    this.service.SearchAgain(this.username);
  }

  addIssue( title: string,
            body: string,
            assignee: string,
            milestone: number,
            labels: string) {

    var newIssueAdd = {
      // title: title,
      // body: body,
      // assignee: assignee,
      // milestone: milestone,
      // labels: labels
      title: 'test1',
      body: 'ksjdlkafjslkdf',
      assignee: 'sdljflksjadflñdks',
      milestone: 1,
      labels: 'testlbl'
    };

    console.log(newIssueAdd);

    this.service.addIssue(newIssueAdd).subscribe(
        (response) => console.log(response),
        (error) => console.log(error)
      );
   }
}

issue.component.html 我只是使用一个简单的按钮来发送没有任何表格的“问题”,我试图让帖子工作但我不能......

<div class="row">
  <div class="col-md-12">
    <form class="well-lg">
      <div class="form-group">
        <input type="text" class="form-control" placeholder="Search Username..."
               [(ngModel)]="username" name="username" (keyup)="OnSearchUser()">
      </div>
    </form>
  </div>
</div>

<div *ngIf="user">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">{{user.name}}</h3>
    </div>
    <div class="panel-body">
      <div class="row">
        <div class="col-md-4">
          <img src="{{user.avatar_url}}" alt="" class="img-thumbnail">
          <a href="{{user.html_url}}" target="_blank" class="btn btn-default btn-block">View Profile</a>
        </div>
        <div class="col-md-8">
          <div class="stats">
            <span class="label label-default">{{user.public_repos}} Public Repositories</span>
            <span class="label label-primary">{{user.public_gists}} Public Github Gists</span>
            <span class="label label-success">{{user.followers}} Followers</span>
            <span class="label label-info">{{user.following}} Following</span>
          </div>
          <br>
          <ul class="list-group">
            <li class="list-group item"><strong>Username: </strong>{{user.login}}</li>
            <li class="list-group item"><strong>Location: </strong>{{user.location}}</li>
            <li class="list-group item"><strong>Email: </strong>{{user.email}}</li>
            <li class="list-group item"><strong>Blog: </strong>{{user.blog}}</li>
            <li class="list-group item"><strong>Member Since: </strong>{{user.created_at}}</li>
          </ul>
        </div>
      </div>
    </div>

    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">User Repositories</h3>
      </div>
      <div class="panel-body">
        <div *ngFor="let re of repo">
          <div class="row">
            <div class="col-md-9">
              <h4><a target="_blank" href="{{re.html_url}}">{{re.name}}</a></h4>
              <button class="btn btn-primary" (click)="addIssue()">Create Issue</button>
              <p>{{re.description}}</p>
            </div>
            <div class="col-md-3">
              <span class="label label-default">{{re.watchers}} Watchers</span>
              <span class="label label-default">{{re.forks}} Forks</span>
            </div>
          </div>
          <hr>
        </div>
      </div>
    </div>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

在你的addIssue方法中,应该是什么类型的表单?看起来它被放入URL中,当它应该作为文档here中引用的body参数传入时:

  

post(url:string,body:any,options?:RequestOptionsArgs):Observable