首页 > 解决方案 > 域模型不起作用 - Angular 6 & core.net 2 REST with Webpack

问题描述

我有以下问题...

环境: IDE:VS2017 项目:Angular 6 和 .Net core 2 配置了 webpack 开发系统:Win-Server 2012 R2 测试:VS2017 使用 IIS Express 和 Chrome 的调试模式

版本和配置:

包.json:

webpack.config.js:

    const path = require('path');
    const webpack = require('webpack');
    const merge = require('webpack-merge');
    const AotPlugin = require('@ngtools/webpack').AotPlugin;
    const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;

        module.exports = (env) => {
        // Configuration in common to both client-side and server-side bundles
        const isDevBuild = !(env && env.prod);
        const sharedConfig = {
            stats: { modules: false },
            context: __dirname,
            resolve: { extensions: [ '.js', '.ts' ] },
            output: {
                filename: '[name].js',
                publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
            },
            module: {
                rules: [
                    { test: /\.ts$/, use: isDevBuild ? ['awesome-typescript-loader?silent=true', 'angular2-template-loader', 'angular2-router-loader'] : '@ngtools/webpack' },
                    { test: /\.html$/, use: 'html-loader?minimize=false' },
                    { test: /\.css$/, use: [ 'to-string-loader', isDevBuild ? 'css-loader' : 'css-loader?minimize' ] },
                    { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
                ]
            },
            plugins: [new CheckerPlugin()/*, new webpack.ProvidePlugin({
                $: "jquery",
                jQuery: "jquery"
            })*/]
        };

        // Configuration for client-side bundle suitable for running in browsers
        const clientBundleOutputDir = './wwwroot/dist';
        const clientBundleConfig = merge(sharedConfig, {
            entry: { 'main-client': './app/boot.browser.ts' },
            output: { path: path.join(__dirname, clientBundleOutputDir) },
            plugins: [
                new webpack.DllReferencePlugin({
                    context: __dirname,
                    manifest: require('./wwwroot/dist/vendor-manifest.json')
                })
            ].concat(isDevBuild ? [
                // Plugins that apply in development builds only
                new webpack.SourceMapDevToolPlugin({
                    filename: '[file].map', // Remove this line if you prefer inline source maps
                    moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
                })
            ] : [
                // Plugins that apply in production builds only
                new webpack.optimize.UglifyJsPlugin(),
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, './app/app.module#AppModule'),
                    exclude: ['./**/*.server.ts']
                })
            ])
        });

        // Configuration for server-side (prerendering) bundle suitable for running in Node
        const serverBundleConfig = merge(sharedConfig, {
            resolve: { mainFields: ['main'] },
            entry: { 'main-server': './app/boot.server.ts' },
            plugins: [
                new webpack.DllReferencePlugin({
                    context: __dirname,
                    manifest: require('./app/dist/vendor-manifest.json'),
                    sourceType: 'commonjs2',
                    name: './vendor'
                })
            ].concat(isDevBuild ? [] : [
                // Plugins that apply in production builds only
                new AotPlugin({
                    tsConfigPath: './tsconfig.json',
                    entryModule: path.join(__dirname, './app/app.module#AppModule'),
                    exclude: ['./**/*.browser.ts']
                })
            ]),
            output: {
                libraryTarget: 'commonjs',
                path: path.join(__dirname, './app/dist')
            },
            target: 'node',
            devtool: 'inline-source-map'
        });

        return [clientBundleConfig, serverBundleConfig];
        };

相关代码(片段):

我的服务方法:

    getTimeTracking(userId: string, year: number, month: number): Promise<TimeTracking> {
        const url = `${this.timeTrackingsUrl}/${userId}/${year}/${month}`;
        return this.clientHttp.get<TimeTracking>(url)
            .toPromise<TimeTracking>()
            .catch(this.handleError.bind(this));
    }

领域模型类(这里:TimeTracking):

export class TimeTracking implements Serializable<TimeTracking> {
    id: string = '';
    userId: string = '';
    month: Date = new Date(0);
    timeTrackingEntries: TimeTrackingEntry[] = [];
    status: TimeTrackingStatus = 0;

    [... more code ...]

    isReadOnly(): boolean {
        return (this.status == TimeTrackingStatus.Saved);
    }

    [... more code ...]
}

我的组件:

@Component({
    moduleId: module.id.toString(),
    templateUrl: 'time-tracking.component.html'})
export class TimeTrackingComponent implements OnInit {

    timeTracking: TimeTracking | undefined;

    [... more code ...]

    this.timeTrackingService.getTimeTracking(this.currentUser.userid, this.selectedMonthDate.getFullYear(), this.selectedMonthDate.getMonth() + 1)
        .then(timeTracking => {
            if (this.timeTrackingForm) {
                this.timeTrackingForm.reset();
            }
            this.timeTracking = timeTracking;
        })

    [... more code ...]
}

这里是我的这个组件的 html:

    <button type="submit" class="btn btn-primary" [disabled]="!timeTrackingForm.form.valid || (timeTracking?.isReadOnly())" (click)="save()">Save</button>

我的问题:

一切都会编译,webpack 构建也没有问题。当我开始使用 VS2017 - IIS Express 进行调试时,将启动服务器并打开 Chrome。我导航到相关页面并通过网络概述可以说 API 调用成功并且数据已传输。但我在开发人员选项的 Chrome 控制台中收到此错误:

错误类型错误:_co.timeTracking.isReadOnly 不是函数

API-调用成功

如果我设置断点,我确定数据对象未映射到我的域模型对象中:

API 数据是对象类型!

问题:

  1. 为什么我的数据没有用“get()”映射到指定的域模型对象?
  2. 我有什么问题吗?
  3. 如何实现使用我的域模型(其中数据对象具有函数)?

谢谢你的帮助...

标签: angularwebpackvisual-studio-2017

解决方案


推荐阅读