冒险进入Angular 2和TypeScript的世界并遇到此错误。看起来你可以在某处设置_isScalar ......只是不确定它应该在哪里。
我收到以下错误(请参阅代码中的注释行):
类型'Rating []'不能分配给'Observable'类型。 “评级[]”
类型中缺少属性“_isScalar”以下代码:
import { Injectable } from '@angular/core';
import { Inject } from '@angular/core';
import { Jsonp, JsonpModule, Http } from '@angular/http';
import { Rating } from './rating.model';
import { Observable } from 'rxjs/Rx';
import { DOCUMENT } from '@angular/platform-browser'
import { IODataList } from '@microsoft/sp-odata-types';
import { SPHttpClient, SPHttpClientConfigurations, SPHttpClientConfiguration, SPHttpClientResponse, ODataVersion, ISPHttpClientConfiguration } from '@microsoft/sp-http';
@Injectable()
// See: http://www.telerik.com/kendo-angular-ui/components/dropdowns/dropdownlist/#toc-data-binding
export class RatingsService {
//constrauctor( private jsonp: Jsonp) { }
constructor(@Inject(Http) private http: Http, @Inject(DOCUMENT) private document: any) { }
//var url = this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$filter=Hidden eq false`;
private choices: Array<Rating> = [];
public fetchData(): Observable<Rating[]> {
console.log("BGW: Document location = " + document.location.href);
// var url = this.context.pageContext.web.absoluteUrl + `/_api/web/lists?$filter=Hidden eq false`;
//var response = this.jsonp.get(url); //.map((response => response.json()));
console.log("BGW: Ratings choices url = " + url);
//var choices: Array<Rating> = new Array<Rating>();
var choices: Array<Rating> = new Array<Rating>();
// choices._isScalar = true;
//let choices: Observable<Rating[]> = new Observable<Rating>();
if (document.location.href.indexOf("localhost") > 0)
{
// Send dummy data to the form.
console.log("BGW: Local workbench in use");
choices.push(new Rating("High"));
choices.push(new Rating("Medium"));
choices.push(new Rating("Low"));
return choices; // *** ISSUE HERE ***
}
else
{
var url = "https://somewhere.sharepoint.com/sites/Development/Subsite/_api/web/lists/GetByTitle('Requirements')/fields?$filter=EntityPropertyName%20eq%20%27Requirement_x0020_Rating%27";
console.log("BGW: Ratings choices url = " + url);
// Ref: http://chariotsolutions.com/blog/post/angular2-observables-http-separating-services-components/
var response = this.http.get(url).map((response => response.json()));
console.log("BGW: response = " + JSON.stringify(response));
return response.map((choices: Array<any>) => {
if (choices) {
choices.forEach((choice) => {
choices.push(new Rating(choice));
});
}
return choices;
});
}
}
}
答案 0 :(得分:2)
问题是因为你没有像你指定的那样返回一个observable:
public fetchData(): Observable<Rating[]>
但稍后您正在定义......
var choices: Array<Rating> = new Array<Rating>();
这就是你收到错误的原因。 Observable Array和“regular”Array之间存在不匹配。如果您没有明确 需要 来指定要返回的内容,我只会完全删除Observable<Rating[]>
。
答案 1 :(得分:0)
你需要返回一个类似的观察点:
return Observable.of<Rating[]>(choices);
使用静态方法of,但还有很多其他方法。
您看到编译器错误的原因是您在方法签名中指定了返回类型:
public fetchData(): Observable<Rating[]>