无法在angular5中调用rest api

时间:2018-02-03 13:44:10

标签: angular rest api angular5

我正在尝试使用以下API(这是开源)从角度5 App:https://jsonplaceholder.typicode.com/users

enter image description here

下面是我的组件

import { Component, OnInit,Injectable, NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Router } from '@angular/router';
import { UserData } from './login';
import {HttpModule, Http, URLSearchParams,,Response, Headers, RequestOptions} from '@angular/http';
import { HttpClient,HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import {BrowserModule} from '@angular/platform-browser';
import {platformBrowserDynamic} from '@angular/platform-browser-dynamic';
import 'rxjs/add/operator/toPromise';
import 'rxjs/Rx';;
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { LoginService }  from 'app/login/login.service';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  isValid:boolean;
 inputEmailModal: string;
 inputPasswordModal: string;
 isValid = false;
 constructor(private http: HttpClient){ }
 constructor(private router: Router) { }
 constructor(private loginService: LoginService){ }
title = 'app works!';
   users;


login(){
  //this.users = loginService.getUsers();
  let headers: Headers = new Headers();
   let opts: RequestOptions = new RequestOptions();
   opts.headers = headers;
         let url = 'https://jsonplaceholder.typicode.com/users';
   this.http.get(url,opts).subscribe(
       res => console.log("success"),
       msg => console.log('error'));
}
}

请建议一些示例代码来调用angular5中的API

1 个答案:

答案 0 :(得分:1)

像这样使用角度HttpClient

将此类导入您的组件

import { HttpClient } from '@angular/common/http';

在构造函数中将此服务注入到组件中

constructor(private http: HttpClient) {
}

方法示例:

public login( userName: string, Password: string ): any { 

    let header: HttpHeaders = new HttpHeaders();
    header = header.set('Content-Type', 'application/json');
    header = header.append('Accept', 'application/json');

            return this.http.post('/api/Token/Get', {"username":userName,"password":Password} 
                                              , { headers:header });
        }

调用示例方法,如下所示:

  login() {

  this.login(this.userName, this.password)
  .subscribe(res => {
    if (res != null) {
      localStorage.setItem('access_token', res.access_token);

      let tokenInfo = this.assistant.getDecodedAccessToken(res.access_token);
     // do some things;
  }
    , (err) => {
     // do some things;
    }
  , () => {
    // do some things;
  }) ; 
}