Angular Httpclient没有命中后端API

时间:2018-02-20 06:35:33

标签: angular angular-httpclient

我有以下代码来使用Play应用程序提供的后端API。如果我在浏览器窗口上按原样输入API http://localhost:9000/ws/users/get(我在窗口上看到响应hello from get user controller,在我的播放应用程序中看到调试打印`get user request),但是import { Injectable } from '@angular/core'; import { environment } from 'environments/environment'; import {Observable} from "rxjs/Observable"; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import { HttpClient} from '@angular/common/http'; import {User} from "./user"; @Injectable() export class WebToBackendInterfaceService { API_URL = environment.apiUrl; ADD_USER_URL = environment.addUserUrl; GET_USER_URL = environment.getUserUrl; constructor(private http:HttpClient) { } public createUser(user:User):any{ console.log('contacting server at '+this.API_URL +this.ADD_USER_URL +" with user data ",user); //if I click this link directly fro browser's debug window then I see response from the server this.http.post(this.API_URL +this.ADD_USER_URL,user) .map(response => { console.log('response from backend service',response); return response; }) .catch(this.handleError); //error handler if Observable fails } public getUser(id:string):any{ console.log('contacting server at '+this.API_URL +this.GET_USER_URL +" with user data "+id); this.http.get(this.API_URL+this.GET_USER_URL) .map(response=>{ console.log('response from backend service',response); return response; }) .catch(this.handleError); } private handleError (error: Response | any) { console.error('WebToBackendInterfaceService::handleError', error); return 'error from the server:'+error; } 可用,但Angular代码没有似乎向后端发送任何内容(我在播放或浏览器窗口中根本看不到任何调试)。

问题1 - 如何调试Angular发送消息的位置 问题2 - 为什么代码不起作用?

new Date()

}

1 个答案:

答案 0 :(得分:1)

所以这里是通过角度

的服务器调用的简单演示

您的应用中必须有service.ts文件,该文件将连接到后端服务器,此文件通常用于服务器和前端之间的连接。

import { Injectable } from '@angular/core';
import {ColaboratorResponse} from '../domain/colaborator.response';
import {Colaborator} from '../domain/colaborator';
import { Headers, RequestOptions, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map';

export class YourService{

constructor(private httpClient: HttpClient) {}
getUser(id:string){   
   return this.httpClient.get(this.API_URL+this.GET_USER_URL);
}

现在您必须在组件中使用此服务。无论你想在哪里调用这个getUser函数,如

首先导入您的服务

import {ColaboratorService} from 'from/your/service/location';

在组件构造函数

中初始化它
constructor(
       private confirmationService: ConfirmationService,
       private _ser: YourService
     ) {}

并通过创建函数

在组件中调用它
getUserDetails(){
this._ser.getUser(id).subscribe((User : any)=>{this.User =User;});

//console.log('here'+this.User);


}

所以这是你的this.User对象

import {User} from "./user";

希望这会有所帮助。