Angular Httpclient没有命中后端API [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有以下代码来使用Play应用程序提供的后端API。如果我在浏览器窗口上按原样输入API http://localhost:9000/ws/users/get(我在窗口看到响应hello from get user controller,在我的播放应用程序中看到调试打印`get user request),但是Angular代码似乎没有发送任何内容到后端(我在播放或浏览器窗口中根本看不到任何调试)。

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

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 angular-httpclient
1个回答
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";

希望这可以帮助。

© www.soinside.com 2019 - 2024. All rights reserved.