从HttpModule转换为HttpClientModule

时间:2017-09-20 20:45:03

标签: angular http rxjs reactivex angular-httpclient

Angular正在从HttpModule转换为HttpClientModule并弃用前者,详见Difference between HTTP and HTTPClient in angular 4?

然而,https://angular.io/tutorial/toh-pt6的Angular教程使用HttpModule,而https://angular.io/guide/http的基础信息使用HttpClientModule,详见https://github.com/angular/angular/issues/19280。使用内存服务器的教程比较困难,而基础知识使用真正的Web服务器。

我尝试使用真实的Web服务器在Angular教程代码中从HttpModule切换到HttpClientModule,并使一些部分工作,但其他部分无法正常工作。它似乎可以改变来自

的hero.services.ts中的一个getHeroes方法
  getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json().data as Hero[])
      .catch(this.handleError);
  }

  getHeroes(): Promise<Hero[]> {
    return this.httpClient.get(this.heroesUrl)
      .toPromise()
      .then(data => data['heroes'] as Hero[])
      .catch(this.handleError);
  }

虽然可能有一些方法可以改进,但这个版本可能有问题我还没有发现。

但是我没有在hero-search.service.ts中看到等效的搜索方法

  search(term: string): Observable<Hero[]> {
    return this.http
      .get(`api/heroes/?name=${term}`)
      .map(response => response.json().data as Hero[]);
  }

一个人应该可以省去地图,但你不能使用与上面相同的方法,因为有一个Observable而不是Promise,你会得到如下错误:

Type 'Observable<Object>' is not assignable to type 'Observable<Hero[]>'.

有没有人在Angular教程中转换Heroes演示以使用HttpClientModule或知道如何转换上面的搜索代码?

2 个答案:

答案 0 :(得分:4)

当HttpClient将JSON响应解析为Object时,它不知道该对象的形状。因此,您可以指定响应的类型:

import numpy as np
import cv2
import glob

# termination criteria in this, 30 max number of iterations, 0.001 minimum accuracy
# CV_TERMCRIT_ITER or CV_TERMCRIT_EPS, tells the algorithm that we want to terminate either after some number of iterations or when the convergence metric reaches some small value (respectively).
# The next two arguments set the values at which one, the other, or both of these criteria should terminate the algorithm.
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

# prepare object points, like (0,0,0), (1,0,0), (2,0,0), ..., (6,5,0)
objp = np.zeros((6*9,3), np.float32)
objp[:,:2] = np.mgrid[0:9,0:6].T.reshape(-1,2)

# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.

images = glob.glob('*.jpg')

# fname= 'C:\\Users\\Bender\\Desktop\\fotospayloads\\'

for fname in images:
    img = cv2.imread(fname)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # Find the chess board corners
    ret, corners = cv2.findChessboardCorners(gray, (9,6), None)

    # If found, add object points, image points (after refining them)
    if ret == True:
        objpoints.append(objp)

        corners2 = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
        imgpoints.append(corners2)

        # Draw and display the corners
        img = cv2.drawChessboardCorners(img, (9,6), corners2, ret)
        cv2.imshow('img', img)
        cv2.waitKey(500)

cv2.destroyAllWindows()

rms, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)

请注意,您可以为其创建界面:

return this.http
    .get<{ data: Hero[] }>(`api/heroes/?name=${term}`)
    .map(res => res.data);

如果您怀疑将要或不想创建界面的响应类型,那么只需使用interface ItemsResponse { data: Hero[]; } return this.http .get<ItemsResponse>(`api/heroes/?name=${term}`) .map(res => res.data);

any

<强> TOH-HttpClientModule Example

另见

答案 1 :(得分:0)

重写你的组件,他们在httpClient中删除了response.json,不再需要调用response.json()。如果数据不是响应的正确名称,请打开控制台并查找返回对象的正确名称。

search(term: string): Observable<Hero[]> {
return this.http
  .get(`api/heroes/?name=${term}`)
  .map(response => {
         console.log(response);
         return response['data'] as Hero[]
   });

}