类型'Observable <object>'不能分配给'Observable <iuser []>'

时间:2018-02-17 03:45:28

标签: javascript angular typescript interface observable

在我的Api服务中,我有这个简单的getUsers函数来获取api上的所有用户。

public getUsers(url: string): Observable<IUser[]>  {
  return this._http.get(url);
} 

这是我的IUser界面,我现在已将所有字段设为可选。

export interface IUser {
  id?: string;
  first_name?: string;
  last_name?: string;
  location?: string;
  followers?: string;
  following?: string;
  checkins?: string;
  image?: string;
}

以下是我在组件中使用该服务的方法:

export class SocialOverviewContainerComponent implements OnInit {
  public userData = [];
  public showForm = {};
  private _apiService: ApiService;

  constructor(apiService: ApiService) {
    this._apiService = apiService
  }

  public ngOnInit(): void {
    this.getUsersData();
  }

  public getUsersData()  {
    this._apiService.getUsers(ApiSettings.apiBasepath + 'users/')
      .subscribe(users => {
        this.userData = users;
    })
  }
}

这是我编译时得到的Type错误

ERROR in src/app/services/api.service.ts(18,5): error TS2322: Type 'Observable<Object>' is not assignable to type 'Observable<IUser[]>'.
  Type 'Object' is not assignable to type 'IUser[]'.
    The 'Object' type is assignable to very few other types. Did you mean to use the 'any' type instead?
      Property 'includes' is missing in type 'Object'.

我认为这可能是因为我的回复与界面不匹配,我已经仔细检查了它。而且我现在也已选择该字段以确保。

我知道我可以通过将observable转换成任何一个来解决这个问题,但这不会破坏使用Typescript的意义吗?

任何有关我出错的地方的帮助都很棒

提前致谢

4 个答案:

答案 0 :(得分:18)

有两种方法可以做到这一点,它取决于您使用的RxJS / Angular版本。以下是根据您的版本执行此操作的两种方法:

// Using RxJS v4 / Angular v2-4. I assume that you're using the HttpModule...
import 'rxjs/add/operator/map';

public getUsers(url: string): Observable<IUser[]> {
  return this._http.get(url)
    .map((response: Response) => <IUser[]>response.json());
}


// Using RxJS v5 / Angular 5+ (at the moment). I assume that you're using the HttpClientModule, as the HttpModule was deprecated in Angular v4.
public getUsers(url: string): Observable<IUser[]> {
  return this._http.get<IUser[]>(url);
}

答案 1 :(得分:5)

典型的,我发布后5分钟,我找到了解决方案。

Trick将服务中的.get函数与getUsers函数中的类型相同,如下所示:

public getUsers(url: string): Observable<IUser[]>  {
    return this._http.get<IUser[]>(url);
  }

希望这也可以帮助其他人

答案 2 :(得分:2)

在我的情况下,以下方法有效

  getUsers(): Observable<User[]> {
      return <Observable<User[]>> this.http.get(this.pathAPI + 'user', super.header())
      .pipe(catchError(super.handleError));
   }

我正在使用Angular 6

答案 3 :(得分:0)

就我而言,几个参数值是数字类型。我需要转换为字符串来解决这个问题。

const params = new HttpParams()
    .set('someparam1', myNumberproperty1.toString())  
    .set('someparam2',myNumberproperty2.toString());