【发布时间】:2018-01-19 01:39:37
【问题描述】:
我从 Angular 4 升级到 5,但出现类型错误。
Type 'Observable<{}>' is not assignable to type 'Observable<Device[]>'
我不确定如何解决这个问题。我确实看到了这个帖子:Type 'Observable<any>' is not assignable to type '[]'。但我不知道如何使用它来解决我的问题。
这是 ts 文件:
import {Component, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import {ListDeviceService} from '../../services/list-device.service';
interface Device {
name: string;
id: string;
}
@Component({
selector: 'app-product',
templateUrl: './product.component.html'
})
export class ProductComponent implements OnInit {
devices: Observable<Device[]>;
constructor(private listDeviceService: ListDeviceService) {
}
ngOnInit() {
const scope = this;
this.listDeviceService.getMyDevices().then(function (data) {
scope.devices = Observable.of(data);
});
}
}
这里是 list-device.service
import {Injectable} from '@angular/core';
import {AuthenticationService} from '../services/authentication.service';
@Injectable()
export class ListDeviceService {
constructor(private authenticationService: AuthenticationService) {
}
getMyDevices() {
const scope = this;
return new Promise((resolve, reject) => {
const token = this.authenticationService.getToken();
const devicesPr = this.authenticationService.getPartsAPI().listDevices({auth: token});
devicesPr.then(
function (devices) {
console.log('list', devices.body);
resolve(devices.body);
},
function (err) {
reject(err);
}
);
});
}
}
这是 package.json:
"dependencies": {
"@angular/animations": "^5.0.0",
"@angular/common": "^5.0.0",
"@angular/compiler": "^5.0.0",
"@angular/core": "^5.0.0",
"@angular/forms": "^5.0.0",
"@angular/http": "^5.0.0",
"@angular/platform-browser": "^5.0.0",
"@angular/platform-browser-dynamic": "^5.0.0",
"@angular/platform-server": "^5.0.0",
"@angular/router": "^5.0.0",
"@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.3",
"angular-ui-bootstrap": "^2.5.0",
"bootstrap": "^3.3.7",
"core-js": "^2.5.1",
"express": "^4.15.4",
"ng2-file-upload": "^1.2.1",
"ngx-modialog": "^3.0.4",
"ngx-pipes": "^1.6.5",
"rxjs": "^5.5.2",
"zone.js": "^0.8.14"
},
"devDependencies": {
"@angular/cli": "1.3.2",
"@angular/compiler-cli": "^5.0.0",
"@angular/language-service": "^4.2.4",
"@types/jasmine": "~2.5.53",
"@types/jasminewd2": "^2.0.3",
"@types/node": "~6.0.60",
"codelyzer": "~3.1.1",
"jasmine-core": "~2.6.2",
"jasmine-spec-reporter": "~4.1.0",
"karma": "^1.7.1",
"karma-chrome-launcher": "~2.1.1",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.3.2",
"typescript": "~2.4.2"
}
【问题讨论】:
-
ListDeviceService 中有什么?
-
告诉我们
ListDeviceService -
bryan60 的解决方案有效。但我添加了列表设备服务。如果您有更好的建议,请告诉我。
标签: angular typescript