八、angular6-http get post请求及跨域

1.app.module.ts引入HttpClientModule

  imports: [
    BrowserModule,
    FormsModule,
    HttpClientModule
  ]

2.新建my-first-servce.service.ts

ng g s my-first-servce

 添加get和post接口请求

import {Injectable} from "@angular/core";
import {HttpClient, HttpHeaders} from "@angular/common/http";
import {Observable} from "rxjs/Rx";
@Injectable({
  providedIn: 'root'
})
export class MyFirstServceService {
  httpOptions = {
    headers: new HttpHeaders({'Content-Type': 'application/json;charset=utf-8'})
  };

  public anyList: any;
  message: string = '我是服务信息';

  /**
   * get请求
   * @param info
   */
  status(info: Object): any {
    return this.http.get("/api/API/Status")
      .pipe(
        res => {
          this.anyList = res;
          return this.anyList;
        }
      )
  }



  /**
   * post请求
   * @param url
   * @param param
   * @returns {Observable<ObservedValueOf<Observable<never>>|any>}
   */
  addUser(url:string, param): Observable<any[]> {
    return this.http.post(url, param, this.httpOptions)
      .pipe(
        res => {
          this.anyList = res;
          return this.anyList
        }
      )
  }

  constructor(private http: HttpClient) {

  }
}

my-first-componnet.component.ts 获取service的get和post方法

 constructor(private renderer: Renderer2,  private myFirstServceService: MyFirstServceService) {
    //单独的get请求
    myFirstServceService.status("1123").subscribe(
      data =>{
        console.log("getResponse is :",  data);
      }
    );
    //单独的post请求
    this.myFirstServceService.addUser(this.url, this.param).subscribe(data => {
      console.log('data', data)
    })
  }

如果是跨域请求,在根目录下添加proxy.config.json文件

{
  "/api": {//在原请求接口前添加api,‘api’可以起其他的名字如原路径:http://localhost:8080/getUsers,新路径http://localhost:8080/api/getUsers
    "target": "http://localhost:8080",//跨域的服务器地址
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true,
    "pathRewrite": {
      "^/api": ""
    }
  }
}

在angular.json文件的serve中添加proxyConfig":"proxy.config.json

"serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "angular6-fundamentals:build",
            "proxyConfig":"proxy.config.json"
          },
          "configurations": {
            "production": {
              "browserTarget": "angular6-fundamentals:build:production"
            }
          }
        },

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Angular 中使用 GET 请求传递数据给后端可以通过以下步骤实现: 1. 引入 HttpClientModule 模块 在 app.module.ts 文件中引入 HttpClientModule 模块: ``` import { HttpClientModule } from '@angular/common/http'; @NgModule({ imports: [ HttpClientModule ] }) export class AppModule { } ``` 2. 创建服务 在创建的服务中定义一个方法,用于发送 GET 请求。例如: ``` import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class DataService { constructor(private http: HttpClient) { } getData(data: any) { return this.http.get('http://localhost:8080/api/data', { params: data }); } } ``` 3. 在组件中使用服务 在需要使用 GET 请求的组件中引入并注入服务,然后调用服务中定义的方法: ``` import { Component } from '@angular/core'; import { DataService } from './data.service'; @Component({ selector: 'app-root', template: ` <button (click)="getData()">Get Data</button> ` }) export class AppComponent { constructor(private dataService: DataService) { } getData() { const data = { name: 'John', age: '30' }; this.dataService.getData(data).subscribe((response) => { console.log(response); }); } } ``` 在上面的例子中,`getData()` 方法调用了 `dataService` 中定义的 `getData()` 方法,并传递了一个包含数据的对象作为参数。在服务中,`params` 属性用于将数据作为查询参数传递给后端。在组件中,通过订阅服务方法返回的 Observable 来获取从后端返回的数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

裂魂人1214

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值