代码之家  ›  专栏  ›  技术社区  ›  Kyle Vassella

使用HttpClient和RXJS向Web API发布数据,凭证:true

  •  2
  • Kyle Vassella  · 技术社区  · 6 年前

    我有一个 Angular 我连接到我的 .NET Web API POST 将一些数据添加到API中。目前我正在使用 HTTP 而不是 HttpClient ,我不发送任何数据。但该服务正在成功连接到API。

    HttpClient 在服役中。到目前为止,我的控制器只是调用我服务的 myFunction() 函数,不传递任何参数,因此没有数据。我不知道房间在哪里 RXJS 附加我的数据的服务的一部分。

    注意:不管我如何实现它,我仍然需要它通过 withCredentials: true ,由于我的API的配置

    Web API控制器:

    namespace api.controllers
    {
        [Authorize]
        public class ValuesController : ApiController
         {
            static List<string> strings = new List<string>()
            {
                "value0", "value1", "value2"
            };
    
            // GET api/values
            public IEnumerable<string> Get()
            {
                return strings;
            }
    
            // GET api/values/5
            public string Get(int id)
            {
                return "value";
            }
    
            // POST api/values
            public void Post([FromBody]string value)
            {
                strings.Add(value);
            }
    
            // PUT api/values/5
            public void Put(int id, [FromBody]string value)
            {
            }
    
            // DELETE api/values/5
            public void Delete(int id)
            {
            }
    
        }
    }
    

    Web API Web。配置文件(CORS设置):

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://localhost:5200" />
        <add name="Access-Control-Allow-Headers" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />
        <add name="Access-Control-Allow-Credentials" value="true" />
      </customHeaders>
    </httpProtocol>
    


    myComponent。组成部分ts:

      myService: MyService;
    
      constructor(myService: MyService) {
          this.myService = myService;
          this.myService.myFunction();
       }
    


    import { Injectable } from '@angular/core';
    import { Http, Response, Request, Headers } from '@angular/http';
    // import { HttpClient, HttpResponse, HttpRequest, HttpHeaders, HttpInterceptor, HttpHandler, HttpEvent } from '@angular/common/http';
    
    import { Observable } from 'rxjs';
    import { from } from 'rxjs';
    import { map, filter, catchError, mergeMap } from 'rxjs/operators';
    
    @Injectable({
      providedIn: 'root'
    })
    
    export class MyService {
      http: Http;
    
      constructor(http: Http) {
        this.http = http;
      };
    
      public myFunction() {
        let request = new Request({
          method: "POST",
          url: "http://localhost:9090/api/values",
          withCredentials: true
        });
    
        return this.http.request(request)
          .pipe(map(res => res.json()))
          .subscribe(
            data => console.warn(data),
            err => console.error(err),
            () => console.log("empty")
          );
      }
    }
    


    http: Http HttpClient ,完成了所有的工作 HttpClient 导入并注释掉 .map/json portions request return this.http.request(request) 当我这样做的时候,我的服务。

    3 回复  |  直到 6 年前
        1
  •  4
  •   Joseph Agbing    6 年前

    我使用这个概念,希望它也能与你合作。

    为数据创建属性类(将其与.NETAPI上的类相匹配),这也提供了简单的数据处理 模型

    export class MyData
    {
     username:string;
     password:string;
     isAuthenticated:boolean;
    }
    

    import { Http, Response, Request, Headers } from '@angular/http';
    
    export class MyService {     
    
      constructor(private http: Http) {}
    
    public myFunction(body:MyData) {
     let url = 'http://localhost:9090/api/values'
        return this.http.post(url,body)
          .pipe(map(res => res.json()))          
      }
    }
    

    TS

    returnValue:any;
    myData:MyData;
    constructor(private service:MyService){
    this.myData = new MyData();
    }
    myFunction()
    {
     this.myData.username = 'anything';
     this.myData.password = 'mypw';
     this.myData.isAuthenticated = true;
    
     this.returnValue = this.service.myFunction(this.myData)
     .subscribe(res=>{console.log(res)})
    }
    

    .NET API

    [HttpPost]
    public void MYAPI([FromBody]MyData model)
    {
    
        string uname = model.username;
        string pw = model.password;
    }
    
        2
  •  1
  •   Muhammed Albarmavi    6 年前

    为了使用HttpClient,您必须导入 HttpClientModule app.module.ts 实例 HttpModule HttpClient 对象实例 http

    @Injectable({
      providedIn: 'root'
    })
    
    export class MyService {
    
      constructor(private http: HttpClient) {
      };
    
      public myFunction(body) {
        let requestOptions = { withCredentials : true };
        return this.http.post("http://localhost:9090/api/values",body,requestOptions);
      }
    }
    

    当您使用HttpClient时,您不需要这样做 .map(res => res.json())

     constructor(myService: MyService) {
          this.myService = myService;
          this.myService.myFunction({username:'test',password:'123465'})
          .subscribe(data => console.warn(data), err => console.error(err),() => console.log("empty")
          );
       }
    

    通常你不需要订阅你的服务,这样你就可以 将数据传输到组件

    恩戈尼特

    作为一般的良好实践,您必须在 恩戈尼特法

    complete guide about http RequestOptions

    最后,这是打字技巧

    这是速记语法

     constructor(private http: HttpClient) {
      };
    

    对此

    private http: HttpClient;
     constructor(http: HttpClient) {
       this.http = http
      };
    
        3
  •  1
  •   M.Laida    6 年前

    除了服务之外,您的代码似乎很好。

    前任:

    const httpOptions = {
     headers: new HttpHeaders({
      'Authorization': myToken
     }),
     withCredentials: true
    };
    

    在您的Http请求上,这样您就不会得到所需的授权错误。

    此参考可能有用: https://angular.io/guide/security

     import { Injectable } from '@angular/core';
     import { HttpClient, HttpHeaders } from '@angular/common/http';
     import { Observable } from 'rxjs';
    
     // api path
     const API_URL = 'http://10.111.1.23:80/api/my_api/api/yourController';
    
     // add http headers.
     const httpOptions = {
        headers: new HttpHeaders({
        'Content-Type': 'application/json'
       })
      };
    
     @Injectable()
     export class MyService {
    
     // inject the Http Client to the constructor
     constructor(private _http: HttpClient) { };
    
     myFunction(entity: any): Observable<yourModel> {
        // using http client the return value of you api is
        // directly map to your model
        return this._http.post<yourModel>(API_URL ,
          entity, httpOptions);
     );
    }