TypeScript/Angular2: rxjs errors TS1138, TS1005, TS1128



我遵循Angular 2教程,当我运行gulp dev时,我在终端中得到这些错误。我使用的是Typescript 2.0.3:

node_modules/rxjs/operator/toPromise.d.ts(8,38): Error TS1138: Parameter declaration expected.
node_modules/rxjs/operator/toPromise.d.ts(8,42): Error TS1005: ';' expected.
node_modules/rxjs/operator/toPromise.d.ts(8,57): Error TS1005: '(' expected.
node_modules/rxjs/operator/toPromise.d.ts(8,58): Error TS1005: ';' expected.
node_modules/rxjs/operator/toPromise.d.ts(8,70): Error TS1005: '(' expected.
node_modules/rxjs/operator/toPromise.d.ts(9,38): Error TS1138: Parameter declaration expected.
node_modules/rxjs/operator/toPromise.d.ts(9,42): Error TS1005: ';' expected.
node_modules/rxjs/operator/toPromise.d.ts(9,57): Error TS1109: Expression expected.
node_modules/rxjs/operator/toPromise.d.ts(9,70): Error TS1005: ';' expected.
node_modules/rxjs/operator/toPromise.d.ts(9,86): Error TS1005: ';' expected.
node_modules/rxjs/operator/toPromise.d.ts(9,87): Error TS1128: Declaration or statement expected.
node_modules/rxjs/operator/toPromise.d.ts(9,99): Error TS1005: '(' expected.

在浏览器中,angular应用不会加载。有人能解释一下这是怎么回事吗?

编辑:这是node_modules/rxjs/operator/toPromise.d.ts 中的第8行和第9行
export declare function toPromise<T>(this: Observable<T>): Promise<T>;
export declare function toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;

这是唯一使用toPromise方法的文件:

weather.service.ts

import {Injectable} from "@angular/core";
import {Http} from "@angular/http";
import "rxjs/add/operator/toPromise";
interface WeatherApiResponse {
    query: {
        count: number;
        created: string;
        lang: string;
        results: {
            channel: {
                item: {
                    condition: {
                        code: string;
                        temp: string
                    }
                }
            }
        }
    };
}
export interface WeatherInformation {
    city: string;
    code: number;
    temperature: number;
}
export interface City {
    name: string;
    imageSrc: string;
    woeId: string;
}
@Injectable()
export class WeatherService {
    cities = [
        {name: "Bogota", imageSrc: "img/bogota.jpg", woeId: "368148"}
    ];
    constructor(private http: Http) {}
    getWeather(woeId: string) {
        const url = this.generateWeatherUrl(woeId);
        return this.http.get(url).toPromise()
            .then(x => {
                const apiResponse = x.json() as WeatherApiResponse;
                const weather = apiResponse.query.results.channel.item.condition;
                return {
                    city: this.getCityName(woeId),
                    code: Number(weather.code),
                    temperature: Number(weather.temp)
                } as WeatherInformation;
            });
    }
    private generateWeatherUrl(woeId: string) {
        return `http://localhost:8001/api/weather/${woeId}`;
    }
    private getCityName(woeId: string) {
        const matches = this.cities.filter(x => x.woeId === woeId);
        return matches.length === 1 ? matches[0].name : undefined;
    }
}

这个函数调用weather.service.ts

中的getWeather()方法

weather.component.ts

ngOnInit() {
    this.route.params.subscribe(params => {
        const woeId = params["woeId"];
        this.weatherService.getWeather(woeId)
            .then(x => this.weather = x);
    });
}

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": true,
    "noImplicitAny": true
  },
  "exclude": [
    "node_modules",
    "typings/main",
    "typings/main.d.ts"
  ]
}

对于那些使用Levi Botelho提出的gulp配置的Packt Angular 2项目,并且对天气应用程序有相同问题的人来说,可以通过更新依赖项(@angular)来解决这个问题。

与以下依赖项一起工作:

  "dependencies": {
    "@angular/common": "~2.1.1",
    "@angular/compiler": "~2.1.1",
    "@angular/core": "~2.1.1",
    "@angular/forms": "~2.1.1",
    "@angular/http": "~2.1.1",
    "@angular/platform-browser": "~2.1.1",
    "@angular/platform-browser-dynamic": "~2.1.1",
    "@angular/router": "~3.1.1",
    "@angular/upgrade": "~2.1.1",
    "angular-in-memory-web-api": "~0.1.13",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "systemjs": "0.19.39",
    "zone.js": "^0.6.25",
    "compression": "^1.6.2",
    "es6-shim": "^0.35.1",
    "express": "^4.14.0",
    "rxjs": "5.0.0-beta.12"
  } 

检查gulp.js文件,因为视频中的gulp.js文件与您可以下载的代码中的gulp.js文件不同…

const argv = require("yargs").argv;
const browserify = require("browserify");
const browserSync = require("browser-sync").create();
const buffer = require("vinyl-buffer");
const cache = require("gulp-cached");
const concat = require("gulp-concat");
const exec = require('child_process').exec;
const gulp = require("gulp");
const gulpIf = require("gulp-if");
const htmlmin = require("gulp-htmlmin");
const inject = require("gulp-inject");
const sass = require("gulp-sass");
const source = require("vinyl-source-stream");
const sourcemaps = require("gulp-sourcemaps");
const tsify = require("tsify");
const tslint = require("gulp-tslint");
const uglify = require("gulp-uglify");
const watchify = require("watchify");
const rootBuildPath = "./dist/";
const cssBundleName = "site.css";
const cssBundleBuildPath = rootBuildPath + "/css/" + cssBundleName;
const cssSource = "./scss/site.scss";
const cssBuildPath = rootBuildPath + "css";
const fontSource = "./bower_components/weather-icons/font/**";
const fontBuildPath = rootBuildPath + "font";
const htmlSource = "./index.html";
const imgSource = "./img/*.jpg";
const imgBuildPath = "./dist/img";
const jsBundleName = "bundle.js";
const jsBundleBuildDirectory = rootBuildPath + "app";
const jsBundleBuildPath = jsBundleBuildDirectory + "/bundle.js";
const jsSourceDirectory = "./app";
const jsEntryPoint = jsSourceDirectory + "/main.ts";
const jsSource = jsSourceDirectory + "/**/*.ts";
const libSource = [
    "node_modules/es6-shim/es6-shim.min.js",
    "node_modules/es6-shim/es6-shim.map",
    "node_modules/zone.js/dist/zone.min.js",
    "node_modules/reflect-metadata/Reflect.js",
    "node_modules/reflect-metadata/Reflect.js.map",
];
const libBuildPath = rootBuildPath + "/lib";
const serverSource = "./server.js";
const templatesSource = "./app/**/*.html";
const templatesBuildPath = rootBuildPath + "app";
const typings = "./typings/index.d.ts";
function logError(err) {
    console.error(err.message);
    this.emit("end");
}
function shouldMinify() {
    return argv.release;
}
gulp.task("lint", function () {
    gulp.src(jsSource)
        .pipe(tslint({
            formatter: "verbose"
        }))
        .pipe(tslint.report())
        .on("error", logError);
});
var browserifyOptions = {
    debug: !shouldMinify(),
    entries: [jsEntryPoint, typings],
    plugin: [tsify]
};
if (argv.watch) {
    browserifyOptions.cache = {};
    browserifyOptions.packageCache = {};
    browserifyOptions.plugin.push(watchify);
}
var browserifyInstance = browserify(browserifyOptions);
gulp.task("js", ["lint"], function () {
    return browserifyInstance
        .bundle()
        .on("error", logError)
        .pipe(source(jsBundleName))
        .pipe(buffer())
        .pipe(sourcemaps.init({loadMaps: true}))
        .pipe(gulpIf(shouldMinify(), uglify().on("error", logError)))
        .pipe(sourcemaps.write("./"))
        .pipe(gulp.dest(jsBundleBuildDirectory));
});
gulp.task("css", function () {
    return gulp.src(cssSource)
        .pipe(concat(cssBundleName))
        .pipe(sourcemaps.init())
        .pipe(sass({outputStyle: shouldMinify() ? "compressed" : "nested"}))
        .pipe(sourcemaps.write("."))
        .pipe(gulp.dest(cssBuildPath))
        .pipe(browserSync.stream());
});
gulp.task("font", function () {
    return gulp.src(fontSource)
        .pipe(gulp.dest(fontBuildPath));
})
gulp.task("img", function () {
    return gulp.src(imgSource)
        .pipe(gulp.dest(imgBuildPath));
});
gulp.task("lib", function () {
    return gulp.src(libSource)
        .pipe(gulp.dest(libBuildPath));
});
gulp.task("templates", function () {
    return gulp.src(templatesSource)
        .pipe(gulp.dest(templatesBuildPath));
});
gulp.task("html", ["js", "css"], function () {
    return gulp.src(htmlSource)
        .pipe(inject(gulp.src([jsBundleBuildPath, cssBundleBuildPath], {read: false}), {ignorePath: "dist"}))
        .pipe(gulpIf(shouldMinify(), htmlmin({collapseWhitespace: true})))
        .pipe(gulp.dest(rootBuildPath));
});
gulp.task("server", function () {
    return gulp.src(serverSource)
        .pipe(gulp.dest(rootBuildPath));
})
gulp.task("default", ["font", "html", "img", "lib", "templates", "server"]);
gulp.task("html-watch", ["html"], () => browserSync.reload());
gulp.task("js-watch", ["js"], () => browserSync.reload());
gulp.task("templates-watch", ["templates"], () => browserSync.reload());
gulp.task("dev", ["default"], function () {
    exec("node dist/server", function (err, stdout, stderr) {
        console.log(stdout);
        console.error(stderr);
    });
    gulp.watch(htmlSource, ["html-watch"]);
    gulp.watch(jsSource, ["js-watch"]);
    gulp.watch(templatesSource, ["templates-watch"]);
    gulp.watch(cssSource, ["css"]);
    browserSync.init({
        port: 8001,
        proxy: "http://localhost:3011"
    });
});

如果您有其他问题,请下载代码以及与视频中不同的组件/服务

原来我需要将。ts翻译成。js,我以为Visual Studio Code会自动为我做这件事。对于那些有同样问题的人,请访问这个网站并按照步骤2进行操作。

步骤2:创建tasks.json

下一步是设置任务配置。要做到这一点,打开使用⌘+ P的命令调色板,并在配置任务运行器中键入,按输入选择. ...

选择TypeScript - tsconfig.json。这将创建一个tasks.json文件在工作空间.vscode文件夹中。

任务内容。Json文件看起来像这样:

{
  // See http://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "0.1.0",
  "command": "tsc",
  "isShellCommand": true,
  "args": ["-p", "."],
  "showOutput": "silent",
  "problemMatcher": "$tsc"
}

在幕后,我们将tsc解释为外部任务运行器只暴露了一个任务:将TypeScript文件编译成JavaScript文件。我们运行的命令是:tsc -p .

最新更新