HttpParams设置为null

时间:2018-01-25 08:33:27

标签: angular http

我有一个方法发布到我的本地项目,我使用HttpParams()FormBuilder。到目前为止,这是我的代码:

表格:

<form [formGroup]="SearchForm" (ngSubmit)="search(SearchForm.value)" name="SearchForms">
<input type="text" class="form-input-text" formControlName="checkin" value="10:00" width="20" placeholder="10:00" readonly>
<input type="hidden" formControlName="location"  name="location" value="{{location}}">

component.ts:

search(post) 
  {
    const params = new HttpParams().set('location',post.location).set('check_in',post.checkin);

    this.http.request(
            "POST",
            "http://localhost/bobobox/public/api/v1/room/search", 
            {
                responseType:"json",
                params
            })
        .subscribe(data => {
          console.log(data);
        });
  }

在控制台中:

POST http://localhost/bobobox/public/api/v1/room/search?location=null&check_in=null 405 (Method Not Allowed)

我得到2个错误。

  1. post data = null
  2. 方法不允许
  3. 如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

你真的需要你的网址中的params(以及为什么POST这样的话)?也许您想将它们设置为POST主体?在这种情况下,代码可以简化 -

search(post) 
{    
    this.http.post("http://localhost/bobobox/public/api/v1/room/search", { 
        location: post.location,
        check_in: post.checkin
    })
    .subscribe(data => console.log(data));
}

不允许使用该方法的消息...也许您需要发出GET请求而不是POST?这更有可能搜索API:

search(post) 
{    
    const url = `http://localhost/bobobox/public/api/v1/room/search?location={$post.location}&check_in={post.checkin}`;
    this.http.get(url).subscribe(data => console.log(data));
}

您需要在服务器端进行保险。是/api/v1/room/search处理程序在后端实现,它是什么方法(POST / GET)?

最后,关于null,我建议记录.search方法条目参数:console.log(post)。它有必要的属性吗?

答案 1 :(得分:0)

对于 7,8角,如果要在获取请求中发送参数, 您可以使用以下方式。此示例从服务器针对某些特定用户提取帖子。

post-store.ts 文件中, getHttpParams()是我们构造参数的方法。

post-component.ts

import { Component, OnInit, Input } from '@angular/core';
import { OperationsService, PostStoreService, AuthService } from 'client/app/services';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.scss']
})
export class PostsComponent implements OnInit {

  posts$ : Observable<any>;

  constructor(private postStore : PostStoreService) { }

  ngOnInit() {
    this.posts$ = this.postStore.posts;
    this.postStore.getPosts('get-posts' , { userId : this.userId });
  }
}

post.component.html

 <div class="user-post clearfix" *ngFor="let post of posts$ | async; let i=index;">

    <div class="post-content">

        <div class="post-header">

            <div class="row no-gutters">

                <div class="col-6">
                    <div class="user-info">
                    <span class="user-name">{{ post?.user.completeName) }}</span>
                    <span class="user-tag">@{{ post?.user.userName}}</span>
                    </div>
                </div>

                <div class="col-6">
                    <div class="post-time-stamp text-right">
                        <span class="post-date">{{ post?.createdAt | date : 'mediumDate' }}</span>
                        <span class="post-time">{{ post?.createdAt | date : 'shortTime' }}</span>
                    </div>
                </div>

            </div>

        </div>

        <div class="post-text">
            <p>{{ post?.text}}</p>
        </div>

    </div>    
</div>

post-store.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { BehaviorSubject } from 'rxjs';
import { environment } from 'client/environments/environment';
import { Http_Headers } from 'client/app/helpers';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class PostStoreService {

  private readonly dataSubject: BehaviorSubject<any>;
  private dataStore : { data : any };

  constructor(private http: HttpClient) { 
    this.dataSubject = <BehaviorSubject<any>>new BehaviorSubject([]);
    this.dataStore = { data: [] };
  }

  get posts() { return this.dataSubject.asObservable(); }

  /* MAKING GET CALL WITH HTTPCLIENT */  
  getPosts(end_point: string , params? : any){

    return this.http.get(`${environment.APIEndPoint + end_point}` , { headers : this.getHttpHeaders() , params : params ? this.getHttpParams( params ) : {} } )
                    .pipe(map((result : any) => result.response))
                    .subscribe(( data : any ) => {
                      console.log('Posts' ,data);
                      this.dataStore.data = data;
                      this.dataSubject.next( Object.assign( {} , this.dataStore).data);
                    },
                    error => console.error('Error' , error));
  }

 /* GETTING HTTPHEADERS */
 getHttpHeaders(): HttpHeaders {
   let headers : HttpHeaders = new HttpHeaders();
   if(localStorage.getItem(JWTOKEN))
   headers = headers.append('Authorization', localStorage.getItem(JWTOKEN));
   headers = headers.append('Access-Control-Allow-Origin', '*');
   headers = headers.append('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PUT, DELETE');
   headers = headers.append("Content-Type" ,  "application/json");
   headers = headers.append("Access-Control-Allow-Credentials" , "true");
   headers = headers.append('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Access-Control-Allow-Origin');
   return headers;
}

/* GETTING HTTPPARAMS*/
getHttpParams(params : any) : HttpParams {
   let httpParams : HttpParams  = new HttpParams();
   Object.keys(params).forEach(key => { 
      httpParams = httpParams.append(key , params[key]);  
   });
    return httpParams;
  }
}