如何编写与jQuery的ajax等效的Angular 8?

时间:2019-10-31 08:42:39

标签: jquery ajax angular typescript angular8

因此,我正在从Webapp的普通旧html和javascript过渡到Angular。因此,我对php服务器控制器的javascript ajax调用需要针对Angular进行重写。我该怎么做?我是第一次使用jQuery写Ajax调用,而对Angular 8还是陌生的。

我想以AngularTS形式编写的jQuery ajax代码

$.ajax({
      data:     DATA,
      url:      '../upgrade/controller/app_validateManager.php',
      dataType: 'json',
      type:     'POST',

        beforeSend: function(x) {
          if (x && x.overrideMimeType) {
            x.overrideMimeType("application/json;charset=UTF-8");
            }
        },  

        success: function(data){
            console.log("works")
            if (data.status == 0)
              {
              alert('Response >> '+data.datr[0]);
              // window.location.href = redirectLink;
              }
            else{
             console.log(prockey + " error")
             console.log(data)
             for(i=0;i<data.errpos.length;i++){
                  $('#err'+data.errpos[i]).innerHtml = data.errmsg[i]
                }
            }
         },
         error: function (xhr, status, errorThrown) {
          //Here the status code can be retrieved like;
          xhr.status;
          //The message added to Response object in Controller can be retrieved as following.
          xhr.responseText;
      }
    });

我尝试过的事情:

// Angular Service code:
const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json;charset=UTF-8"',
  })
};

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an observable with a user-facing error message
  return throwError(
    'Something bad happened; please try again later.');
  }

  ajaxEngine(DATA: PostData): Observable<PostData> {
  console.log(DATA);
    return this.httpClient.post<PostData>(this.phpurl, DATA, httpOptions)
      .pipe(
        retry(3), // retry a failed request up to 3 times
        catchError(this.handleError)
      );
  }

// Angular Component code:
    this.mainService.ajaxEngine(new PostData(newDATA))
    .subscribe(
      data => {
        console.log('works' + data);
        this.postData = data;
      },
      error => {
        console.log(error);
      }
    );

1 个答案:

答案 0 :(得分:0)

您可以使用rxjs / ajax中的ajax来为ajax请求创建一个可观察的对象,然后订阅它以访问接收到的数据或处理错误,请访问此链接以获取更多详细信息: rxjs ajax