是否有任何AngularJS + ASP.NET-的WebAPI +的OData + Breeze.js +打字稿例子还是没人尝试结合这些 [英] Is there any AngularJS + ASP.NET-WebApi + OData + Breeze.js + Typescript examples or did someone try to combine those

查看:257
本文介绍了是否有任何AngularJS + ASP.NET-的WebAPI +的OData + Breeze.js +打字稿例子还是没人尝试结合这些的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着去这些技术结合在一起,但不会有任何好处,因为实体框架元DATAS没有得到通过breeze.js,即使所有的配置安装在什么地方,这是一个有点棘手的局面消耗,也没有字面上的那例,所以这是我的示例code不正常工作,但不知何故,也许会有人发现我的错误,并最终帮助解决这个难题还是会发现它为起点。

Im trying to combine those technologies, but nothing good comes, as entity framework meta-datas doesn't get consumed by breeze.js, even all configurations where setup, it's a bit tricky situation, there is literally no examples of that, so this is my sample code which doesn't work properly, but somehow maybe someone will find my mistake and eventually help to solve this puzzle or will find it as starting point.

OdataService.ts

OdataService.ts

'use strict';
module twine.components {
  class MetadataStoreOptions implements breeze.MetadataStoreOptions{
    namingConvention:breeze.NamingConvention = breeze.NamingConvention.defaultInstance;
  }
  class Manager implements breeze.EntityManagerOptions {
    metadataStore: breeze.MetadataStore;
    constructor( public dataService: breeze.DataService) {
    }
  }
  class DataServiceOptions implements breeze.DataServiceOptions {
    serviceName = 'http://twine.azurewebsites.net/odata';
    hasServerMetadata = true;
  }
  export class ODataService {
    options: Manager;
    manager: breeze.EntityManager;
    metadataStore: breeze.MetadataStore;
    storeOptions: MetadataStoreOptions;
    static $inject: string[] = ['$http', '$rootScope'];
    cache: twine.Model.IEntity[];

    constructor(private $http: ng.IHttpService, private $rootScope: ng.IRootScopeService){
      this.storeOptions = new MetadataStoreOptions();
      this.metadataStore = new breeze.MetadataStore(this.storeOptions);
      this.options = new Manager( new breeze.DataService( new DataServiceOptions() ));
      this.options.metadataStore = this.metadataStore;
      this.manager = new breeze.EntityManager( this.options );
      breeze.config.initializeAdapterInstance('dataService', 'webApiOData', true);
      //this.manager.fetchMetadata((meta) => {
      //  this.metadataStore.importMetadata(meta);
      //});
    }

    All( query:breeze.EntityQuery,  successCallback: Function, failCallback?: Function ): void {
      this.manager.executeQuery( query )
        .then( ( data: breeze.QueryResult ) => {
          successCallback( data );
          this.$rootScope.$apply();
        })
        .catch( ( reason: any ) => {
          if ( failCallback ) {
            failCallback( reason );
          }
        });
    }
    Get( key:number,  successCallback: Function, failCallback?: Function ): void {
      //this.manager.fetchMetadata();
      //var entityType = this.manager.metadataStore.getEntityType('Tag');
      //var entityKey = new breeze.EntityKey(entityType, key);
      this.manager.fetchEntityByKey( 'Tag', key )
        .then( ( data: breeze.EntityByKeyResult ) => {
          successCallback( data );
          this.$rootScope.$apply();
        })
        .catch( ( reason: any ) => {
          if ( failCallback ) {
            failCallback( reason );
          }
        });
    }
  }
}

这是tagController.ts

And this is tagController.ts

'use strict';
module twine.routes {
  interface ITagsScope extends ng.IScope {
    vm: TagsCtrl;
  }
  interface ITagsCtrl extends twine.components.ITwineRoute{
    tags:any[];
    getTags: () => void;
    tag: any[];
    getTag: (id:number) => void;
  }
  export class TagsCtrl implements ITagsCtrl{
    /* @ngInject */
    static controllerId: string = 'TagsController';
    static controllerAsId: string = 'tagsCtrl';
    static $inject: string[] = ["$scope", "ODataService", '$route'];
    entityQueryName: string = 'Tag';
    query: breeze.EntityQuery;
    tags:any;
    tag: any;
    constructor (private $scope: ITagsScope, private ODataService: twine.components.ODataService, $route: ng.route.IRouteService) {
      this.query = new breeze.EntityQuery(this.entityQueryName);
      if($route.current && $route.current.params.id){
        this.getTag($route.current.params.id);
      }
      else {
        this.getTags();
      }
    }
    getTags() {
      this.ODataService.All(this.query , (data) => {
        this.tags = data.results[0].value;
      }, (error) => {
        console.log('error', error);
      });
    }
    getTag(id:number){
      this.ODataService.Get(id , (data) => {
        this.tag = data.results[0].value;
      }, (error) => {
        console.log('error', error);
      });
    }
  }
}

有很多错误,在不同的配置,有时它的没有资源名称为此查询的EntityKey必须设置其他愚蠢的错误这确实没有出现,因为它是一个打字稿不允许类型不匹配,但配置本身是不正确的。

There are many errors, on different configurations, sometimes it's There is no resourceName for this query or EntityKey must be set, or Other stupid errors which are indeed doesn't have to appear because it's a typescript which doesn't allow type mismatches, but the configuration itself is not correct.

这是抽象控制器

[EnableCors(origins: "*", headers: "*", methods: "*")]
public abstract class EntityController<T> : ODataController where T: Entity
{
    protected ODataRepository<T> repo = new ODataRepository<T>();
    private static ODataValidationSettings _validationSettings = new ODataValidationSettings();
    public EntityController()
    {

    }
    // GET: odata/Entity
    [EnableQuery]
    public IQueryable<T> Get(ODataQueryOptions<T> queryOptions)
    {
        try
        {
            queryOptions.Validate(_validationSettings);
        }
        catch (ODataException ex)
        {
            Trace.WriteLine(ex.Message);
            return null;
        }
        return repo.All();
    }

    // GET: odata/Entity(5)
    [EnableQuery]
    public SingleResult<T> Get([FromODataUri] long key, ODataQueryOptions<T> queryOptions)
    {
        try
        {
            queryOptions.Validate(_validationSettings);
        }
        catch (ODataException ex)
        {
            Trace.WriteLine(ex.Message);
            return null;
        }
        return SingleResult.Create(repo.All().Where(x=>x._id == key));
    }
    //ommitted
}

和最后这是ASP.NET的WebAPI配置

And lastly this is ASP.NET webApi configuration

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Конфигурация и службы веб-API
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        // Маршруты веб-API
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        //CORS
        var cors = new EnableCorsAttribute(
            "*",
            "*",
            "*",
            "DataServiceVersion, MaxDataServiceVersion"
        );
        config.EnableCors(cors);

        // Маршруты Odata
        //config.EnableQuerySupport();
        config.AddODataQueryFilter();

        Builder<Account>(config);
        Builder<Branch>(config);
        Builder<Bucket>(config);
        Builder<Ingredient>(config);
        Builder<Like>(config);
        Builder<Meetup>(config);
        Builder<Shot>(config);
        Builder<Skill>(config);
        Builder<Tag>(config);
        Builder<Team>(config);
    }
    private static void Builder<T>(HttpConfiguration config) where T: class
    {
        var entityType = Activator.CreateInstance<T>().GetType();
        if (entityType != null)
        {
            var builder = new ODataConventionModelBuilder();
            builder.EntitySet<T>(entityType.Name);
            config.Routes.MapODataServiceRoute("odata_" + entityType.Name, "odata", builder.GetEdmModel());
        }

    }
}

有关测试的目的,我在 http://twine.azurewebsites.net/odata/Tag 这方面的工作支持的OData服务,(目前还没有通过CORS的限制,随意)最后的实体可以根据配置的WebAPI 构建方法更改为其他名称。请随时提出任何其他信息。如果有人需要整个源代码,即时通讯愿意在GitHub上发布

For testing purpose i have this working backed OData service at http://twine.azurewebsites.net/odata/Tag, (currently no restrictions by CORS, feel free) last entity can be changed to other name based on webApi configuration Build method. Please feel free to ask any other information. If someone need whole source, im willing to publish on github

忘了mension,问题是ODataService的获取方法。我无法从服务器绑定的元数据微风,方法一切工作正常。但查询 fetchByEntityKey 上方

Forget to mension, problem is in method Get of ODataService. I cannot bind metadata from server to breeze, method All works fine. But query fetchByEntityKey throws errors as described above

推荐答案

有一个在微风的样本,尤其是的网页API的OData和微风。这是一个为angularjs +的WebAPI + ODATA +微风样品教程,没有打字稿(而不是仅仅的JavaScript打字稿:)。为了您的网页API控制器,​​你一定要安装该软件包的NuGet:

Have a look at the Breeze samples, especially WEB Api OData and Breeze. It's sample tutorial for a angularjs+webapi+odata+breeze, no typescript (but isn't javascript just typescript :). For your WEB Api controllers you should definitely install this nuget package :

PM> Install-Package Breeze.Server.WebApi2

这将允许你建立一个微风意识到API控制器和metada容易使用Breeze.Server.ContextProviderClass暴露微风ODATA。

This will allow you to build a breeze aware api controller and expose breeze odata metada easily using the Breeze.Server.ContextProviderClass.

这篇关于是否有任何AngularJS + ASP.NET-的WebAPI +的OData + Breeze.js +打字稿例子还是没人尝试结合这些的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆