zoukankan      html  css  js  c++  java
  • ASP。NET Core 1.0 RC2和Angular2使用WEB API

    介绍 在这篇文章中,我们将详细介绍如何在ASP中使用Angular2。NET Core 1.0 RC2使用WEB API。 在上一篇文章中,我们已经了解了一些ASP的基础知识。现在我们将详细了解如何在ASP中使用WEB API和Angular2。网络核心RC2。 在本文中,我们将详细了解如何进行 创建我们的ASP。NET Core 1.0 RC2 Web应用程序。创建MVC模型以添加学生详细信息。创建MVC控制器返回WEB API方法如何添加TypeScript JSON配置文件如何添加grunt包使用NPM配置文件如何配置grunt文件如何创建我们的Angular2应用程序,启动使用类型脚本文件。如何使用Visual Studio任务运行器浏览器运行Grunt文件现在是运行并查看我们的示例的时候了。如何在HTML页面中显示Angular2组件的结果。 参考网站:https://angular。io / docs / ts /最近/教程/, https://angular.io/docs/ts/latest/guide/server-communication.html 先决条件 Visual Studio 2015:你可以从这里下载。 ASP。NET Core 1.0 RC2:下载链接https://www.microsoft.com/net https://www.microsoft.com/net/core#windows 使用的代码 在安装了Visual Studio 2015和ASP之后。NET Core 1.0 RC2。单击“开始”,然后单击“程序”并选择Visual Studio 2015——单击“新建”,然后单击“项目”,选择Web并选择ASP。NET Core Web应用程序。输入项目名称并单击OK。 接下来选择Web Application。如果您没有在云中托管,那么您可以取消勾选右下角的云中的主机。单击OK 现在我们已经创建了ASp。NET Core 1.0 Web应用程序。 步骤2:创建MVC模型来返回学生列表 我们可以通过在模型文件夹中添加一个新的类文件来创建模型。 右键点击模型文件夹并点击新建项目。选择类并输入你的类名为“studentmaster .cs” 现在添加到这个类中,我们首先创建属性变量,添加学生详细信息到列表并返回列表,我们将在控制器中使用这个列表。 隐藏,收缩,复制Code

    public class StudentMasters
        {
            public int StdID { get; set; }
            public string StdName { get; set; }
            public string Email { get; set; }
            public string Phone { get; set; }
            public string Address { get; set; }
    
            public StudentMasters(int ID, string Name, string email, string phone, string Addr)
            {
                StdID = ID;
           StdName = Name;
           Email = email;
            Phone = phone;
                Address = Addr;
        }
    
            public static List<StudentMasters> studetndDetails()
            {
                List<StudentMasters> listStudents = new List<StudentMasters>();
                listStudents.Add(new StudentMasters(1, "Shanu",  "shanu@shanumail.com",  "000000",  "korea"));
                listStudents.Add(new StudentMasters(2, "Afraz", "Afraz@gmail.com", "0000123", "korea"));
                listStudents.Add(new StudentMasters(3, "Afreen", "Afreen@gmail.com", "000643", "Seoul,Korea"));
                listStudents.Add(new StudentMasters(4, "Asha", "Asha@gmail.com", "00003455", "Madurai,India"));
                listStudents.Add(new StudentMasters(5, "Kather", "Kather@gmail.com", "000067567656", "Madurai,India"));
    
                return listStudents;
            }
        }

    步骤3:创建MVC控制器来返回WEB API方法 我们可以通过在控制器文件夹中添加一个新的空API控制器来创建控制器。 右键单击控制器文件夹并添加控制器。选择空API控制器并将其命名为“StudentMastersController” 在我们的Angular2组件中,我们将使用这个web API方法在我们的HTML页面中返回数据和绑定。 隐藏,复制Code

    [Produces("application/json")]
        [Route("api/StudentMasters")]
        public class StudentMastersController : Controller
        {
    
            [HttpGet]
            public IEnumerable<StudentMasters> Get()
            {
                return StudentMasters.studetndDetails().ToList();
            }
        }

    为了测试它,我们可以运行我们的项目并复制get方法的api路径这里我们可以看到get的api路径是api/StudentMasters/ 运行程序并粘贴上面的API路径来测试我们的输出。 步骤4:如何添加TypeScript JSON配置文件 TypeScript JSON文件将指定根文件和编译项目所需的编译器选项。要了解更多关于TypeScript JSON配置,请访问这个网站 http://www.typescriptlang.org/docs/handbook/tsconfig-json.html, 要创建TypeScript JSON文件,右键单击您的项目并单击Add new Item。 选择TypeScript JSCON配置文件并单击ok。文件将看起来像下图。 现在复制下面的代码并用配置文件替换。 隐藏,复制Code

    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "noImplicitAny": false,
        "noEmitOnError": true,
        "removeComments": false,
        "target": "es5",
     "sourceMap": true

    步骤5:如何使用NPM配置文件添加grunt包 现在我们需要添加一个NPM配置文件,以添加一个运行java脚本的grunt包。 由于我们已经创建了一个Web应用程序,NPM配置文件将位于我们的项目中。 默认情况下,我们不能查看NPM配置文件。NPM配置文件的名称为“package”。JSON”。要从解决方案资源管理器查看,请单击“显示所有文件” 现在打开“包”。现在,首先我们需要更改名称为我们的项目解决方案的名称,并添加我们的grunt包,我们可以看到下面的代码。 在这里,我们更改了名称作为解决方案名称,并添加了grunt包。 隐藏,复制Code

    {
      "name": "test",
      "version": "0.0.0",
      "private": true,
    "devDependencies": {
        "grunt": "1.0.1",
        "grunt-contrib-copy": "1.0.0",
        "grunt-contrib-uglify": "1.0.1",
        "grunt-contrib-watch": "1.0.0",
        "grunt-ts": "5.5.1",
        "gulp": "3.8.11",
        "gulp-concat": "2.5.2",
        "gulp-cssmin": "0.1.7",
        "gulp-uglify": "1.2.0",
        "rimraf": "2.2.8"
      }
    }

    现在保存包。json文件,您应该能够看到一个grunt包下的Dependencies/ npm文件夹将首先采取,然后安装。 恢复: 安装: 步骤6:配置Grunt文件。 Grunt用于为我们的项目构建所有客户端资源,比如JavaScript。 第一步是将Grunt文件添加到我们的项目中。右键单击我们的项目,选择Grunt配置文件,然后单击Add。 在创建文件之后,现在我们需要编辑这个文件来添加加载插件,配置插件和定义任务。 在我们的Grunt文件中,我们有我们在npm中添加的第一个加载插件。使用loadNpmTask我们加载'grunt-contrib-copy,'grunt-contrib-uglify”、“grunt-contrib-watch” 接下来配置grunt文件,将app.js文件添加到wwwroot文件夹中。所有来自Scripts文件夹的脚本文件都将添加到这个app.js文件中。接下来我们需要将所有的脚本文件从'node_modules/复制到我们的本地js文件夹中。 手表插件将用于检查JavaScript文件的任何变化,并更新它的app.js与所有新的变化。 隐藏,收缩,复制Code

    /*
    This file in the main entry point for defining grunt tasks and using grunt plugins.
    Click here to learn more. http://go.microsoft.com/fwlink/?LinkID=513275&clcid=0x409
    */
    module.exports = function (grunt) {
        grunt.loadNpmTasks('grunt-contrib-copy');
        grunt.loadNpmTasks('grunt-contrib-uglify');
        grunt.loadNpmTasks('grunt-contrib-watch');
        grunt.loadNpmTasks('grunt-ts');
        grunt.initConfig({
            ts:
            {
                base:
                {
                    src: ['Scripts/app/boot.ts', 'Scripts/app/**/*.ts'],
                    outDir: 'wwwroot/app',
                    tsconfig: './tsconfig.json'
                }
            },
            uglify:
            {
                my_target:
                {
                    files: [{
                        expand: true,
                        cwd: 'wwwroot/app',
                        src: ['**/*.js'],
                        dest: 'wwwroot/app'
                    }]
                },
                options:
                {
                    sourceMap: true
                }
            },
            // Copy all JS files from external libraries and required NPM packages to wwwroot/js  
            copy: {
                main: {
                    files:
                         [{
                             expand: true,
                             flatten: true,
                             src: ['Scripts/js/**/*.js', 'node_modules/es6-shim/es6-shim.min.js', 'node_modules/systemjs/dist/system-polyfills.js', 'node_modules/angular2/bundles/angular2-polyfills.js', 'node_modules/systemjs/dist/system.src.js', 'node_modules/rxjs/bundles/Rx.js', 'node_modules/angular2/bundles/angular2.dev.js'],
                             dest: 'wwwroot/js/',
                             filter: 'isFile'
                         }]
                }
            },
            // Watch specified files and define what to do upon file changes  
            watch: {
                scripts: {
                    files: ['Scripts/**/*.js'],
                    tasks: ['ts', 'uglify', 'copy']
                }
            }
        });
        // Define the default task so it will launch all other tasks  
        grunt.registerTask('default', ['ts', 'uglify', 'copy', 'watch']);
    };

    第7步:添加依赖来安装Angular2和所有其他文件 我们使用NPM在web应用程序中安装Angular2。打开我们的包。JSON文件和下面的依赖关系。 隐藏,复制Code

    "dependencies": {
        "@angular/http": "2.0.0-rc.1",
        "angular2": "^2.0.0-beta.8",
        "angular2-jwt": "0.1.16",
        "angular2-meteor": "0.5.5",
        "cors": "2.7.1",
        "systemjs": "0.19.22",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.2",
        "tsd": "^0.6.5",
        "zone.js": "0.5.15"
      },

    编辑包。json文件将看起来像下图。 保存文件,等待几秒钟,以完成所有正派安装。 步骤8如何创建我们的Angular2应用程序,启动使用类型脚本文件。 现在是创建Angular2应用程序的时候了。首先创建一个名为Scripts的文件夹。右键点击我们的项目,点击添加新文件夹,并将文件夹命名为“Scripts”。现在我们将在这个脚本文件夹中创建TypeScript文件。 要使用Angular2,我们需要创建2个重要的TypeScript文件。 组件文件,我们写Angular代码的地方。启动文件:运行我们的组件应用程序。 创建App TypeScript文件: 右键单击Scripts文件夹,然后单击add new Item。选择TypeScript文件并将该文件命名为App.ts,然后单击Add。 在App.ts文件中,我们有三个部分,首先是 导入部分接下来是组件部分接下来是用于编写业务逻辑的类。 在这里,我们可以看到一个简单的基本单向绑定示例,用于在h1边标签中显示欢迎消息。 导入部分:首先我们导入angular2文件在我们的组件使用我们在angular2进口http使用http客户端组件和进口NgFor使用循环和绑定的所有学生细节数组值一个接一个,我们也进口一个打印稿出口类名StudentMasters模型文件。 隐藏,复制Code

    import { Component, Injectable} from 'angular2/core';
    import { NgFor } from 'angular2/common';
    import {Http, Headers, Response} from 'angular2/http';
    import { StudentMasters } from './model';
    import 'rxjs/Rx';

    ,,,2. 接下来是组成部分: 组件中有选择器、指令和模板。Selector是给这个应用程序命名,在html文件中,我们使用这个选择器名称来显示在html页面中。在模板中我们编写代码。在模板中,我们使用ngFOR绑定StudentMaster细节。学生详细信息将被加载到导出类中,我们在其中编写所有业务逻辑和http函数来从WEB API加载数据。 隐藏,复制Code

    @Component({
        selector: "my-app",
        directives: [NgFor],
        template: `
                <h1style="color:#467813;">ASP.NET Core / Angular2 and WEB API Demo </h1>
    <hr>
      <h2>A Simple demo made by : <spanstyle="color:#8340AF;">{{myName}} </span> </h2>
      
    <h2style="color:#FF5733;"> Student Details retured from WEB API as JSON result  </h2>
     <h3style="color:#C70039;">
       <ul>
          <li*ngFor="let std of student">
       <code> <span*ngFor="let stdArray of generateArray(std)"> {{stdArray}} </span> </code>
    </li>
          
        </ul>
    </h3>
                  `,})

    3.出口类: 这是我们在组件模板中执行所有业务逻辑和变量声明的主要类。在这个类中,我们创建了一个名为getData()的方法,在这个方法中,我们获得API方法结果并将结果绑定到student数组。在组件模板中,我们将绑定这个学生数组的结果。 隐藏,复制Code

    export class AppComponent {
        student: Array<StudentMasters> = [];
        myName: string;
        constructor(public http: Http) {
            this.myName = "Shanu";
            this.getData();
        }
    
        getData() {
    
            this.http.get('api/StudentMasters')
                .map((res: Response) => res.json())
                .subscribe(
                data => { this.student = data },
                err => console.error(err),
                () => console.log('done')
    
                );
        }
        // to generate the JSON object as array
        generateArray(obj) {
            return Object.keys(obj).map((key) => { return obj[key] });
        }
    }

    接下来,我们需要添加引导。ts文件来运行我们的应用程序。 创建启动TypeScript文件: 右键单击Scripts文件夹,然后单击add new Item。选择TypeScript文件并将该文件命名为boot。点击添加。 在引导。我们在ts文件中添加以下代码。这里首先我们导入bootsrap文件来加载和运行我们的应用程序文件,同时我们也导入我们的应用组件。注意,要导入应用程序,我们需要给出与app typescript文件中相同的类名,并在from 中给出应用路径;”。接下来,通过在bootstrap中添加应用名bootstrap(myAppComponent);运行应用程序。 隐藏,复制Code

    ///<reference path="../node_modules/angular2/typings/browser.d.ts" />  
    
    import {bootstrap} from 'angular2/platform/browser'
    import {ROUTER_PROVIDERS} from "angular2/router";
    import {HTTP_PROVIDERS, HTTP_BINDINGS} from "angular2/http";
    import {AppComponent} from './app'
    
    bootstrap(AppComponent, [HTTP_BINDINGS, HTTP_PROVIDERS]);

    创建模型TypeScript文件: 右键单击Scripts文件夹,然后单击add new Item。选择TypeScript文件并将该文件命名为model。点击添加。 我们使用这个模型typescript文件来创建我们的Studentmasters模型,并声明我们在MVC模型中创建的所有公共属性。 隐藏,复制Code

    export class StudentMasters {
        constructor(
            public StdID: number,
            public StdName: string,
            public Email: string,
            public Phone: string,
            public Address: string
        ) { }
    }

    步骤9:创建HTML文件 接下来,我们需要创建html页面来查看结果。要添加HTML文件,右键单击wwwroot文件夹,然后单击添加新项目,将名称命名为index.html,然后单击添加。 在HTMl文件中替换以下代码。这里我们可以看到,首先在头部分,我们添加了所有的脚本引用文件,在脚本中,我们加载我们的引导文件来运行我们的应用程序。在主体部分,我们使用组件选择器的名称显示结果。在我们的应用程序组件,我们给选择器的名称为“myapp1”。在这个HTML中我们添加了这样的标签来显示结果:my-app>Please wait… 隐藏,收缩,复制Code

    <html>
    
    <head>
        <title>ASP.NET Core: AngularJS 2 Demo</title>
        <metaname="viewport"content="width=device-width, initial-scale=1">
        <!-- 1. Load libraries -->
        <!-- IE required polyfills -->
        <scriptsrc="/js/es6-shim.min.js"></script>
        <scriptsrc="/js/system-polyfills.js"></script>
        <!-- Angular2 libraries -->
        <scriptsrc="/js/angular2-polyfills.js"></script>
        <scriptsrc="/js/system.src.js"></script>
        <scriptsrc="/js/Rx.js"></script>
        <scriptsrc="/js/angular2.dev.js"></script>
        <scriptsrc="/js/router.dev.js"></script>
        <scriptsrc="/js/http.dev.js"></script>
        <!-- Bootstrap via SystemJS -->
        <script>
    
            System.config
            ({
                packages:
                {
                    "app":
                    {
                        defaultExtension: 'js'
                    },
                    'lib': { defaultExtension: 'js' }
                }
            });
            System.import('app/boot').then(null, console.error.bind(console));
        </script>
    </head>
    
    <body>
        <!-- Application PlaceHolder -->
        <my-app>Please wait...</my-app>
    
    </body>
    
    </html>

    那么接下来我们已经成功创建了我们的第一个Angular2和Asp。Net core 1.0 web应用程序和等待我们必须再做一个挂起的工作来运行我们的应用程序?是的,我们需要运行我们的Grunt文件来创建我们的整个脚本文件在我们的wwwroot脚本文件夹。 步骤8:使用Visual Studio任务运行器资源管理器运行Grunt文件 现在我们需要使用Visual Studio任务运行器运行Grunt文件。 来查看任务运行点击菜单视图->其他窗口,→然后单击任务运行器 我们也可以通过在解决方案资源管理器中右键单击Gruntfile.js打开任务运行器,然后单击任务运行器资源管理器。 现在我们可以看到任务运行器资源管理器。 单击GruntFile.js并单击左上角的refresh按钮。 现在我们可以看到所有的GruntFile都被添加了。 右键单击别名任务下的默认值,然后单击Run。 现在我们的Grunt文件已经在我们的项目中成功运行。当我们添加一个脚本文件时,我们可以看到新的app.js文件将在我们的wwwroot文件夹中创建。 运行程序: 在这里,我们可以看到所有来自WEB API的数据已经使用Angular2绑定到我们的HTML页面。 历史 ShanuASPNETCoreAngular2WEBAPI.zip——比;2016-07-11 本文转载于:http://www.diyabc.com/frontweb/news17331.html

  • 相关阅读:
    uva 11294 Wedding
    uvalive 4452 The Ministers’ Major Mess
    uvalive 3211 Now Or Later
    uvalive 3713 Astronauts
    uvalive 4288 Cat Vs. Dog
    uvalive 3276 The Great Wall Game
    uva 1411 Ants
    uva 11383 Golden Tiger Claw
    uva 11419 SAM I AM
    uvalive 3415 Guardian Of Decency
  • 原文地址:https://www.cnblogs.com/Dincat/p/13494113.html
Copyright © 2011-2022 走看看