How to send POST Angular 2

0

I am studying Angular 2/4 to be able to use that framework soon, but I am very confused with the POST part.

I am using the Github API to post an "issue" in my repository but I still can not do it ... so I would be very grateful if you can clarify that point to send an "issue" type test to understand how It works in Angular 2/4, since I understand that it has to be sent in "JSON" format to work but I do not understand how ... I'm using the github api: link

Here my code:

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 that 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)
      );

    // this.service.addIssue(newIssueAdd);

  }
}

issue.component.html I'm just using a button to send it for testing because then I'll create a form but I need the "POST" to work

<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>
    
asked by Marco Montoya 07.06.2017 в 03:37
source

1 answer

1

To begin with, the URL is badly formed. As stated in the API documentation, it must have the following structure:

/repos/:owner/:repo/issues
/repos/anubis/LinioAngularProfileListMarcoAntonioVMontoyaCardenas/issues

When the request is POST, there are no parameters for query string, it is necessary to send them as BODY.

For Angular's version < 4.3 would be:

this.http.post(url, 
{
  "title": "Found a bug",
  "body": "I'm having a problem with this.",
  "assignees": [
    "octocat"
  ],
  "milestone": 1,
  "labels": [
    "bug"
  ]
})

Where URL is the one we defined earlier.

Depending on the version of angular that you install is how the request is armed. From version 4.3 of Angular, HttpClient was added.

link

    
answered by 30.03.2018 / 21:50
source