【问题标题】:How do I make an asynchronous call using AngularJs and Typescript如何使用 AngularJs 和 Typescript 进行异步调用
【发布时间】:2015-02-19 21:01:06
【问题描述】:

这似乎是一个非常简单的问题,但对于 Javascript、Typescript 和 Angular 来说,我似乎找不到答案(我看起来相信我)。

我只想向服务器发出一个简单的请求并处理结果。这实际上是 OAuth 身份验证过程的一部分:https://developers.google.com/accounts/docs/OAuth2UserAgent#validatetoken

我找到了很多对 $http.get 的引用,但我不确定如何从 Typescript 中调用它。 我还看到人们在谈论 JQuery 承诺,但我相信如果我已经在使用 Angular,就不需要使用 JQuery。

我查看了我的 angular.d.ts 文件,看起来我应该使用 IHttpService 但如何实例化其中一个?如何将泛型与 get 方法一起使用? 一个如何做到这一点的例子会很棒。

非常感谢您的帮助。

【问题讨论】:

  • 如果您是 javascript 新手并想使用 angular,我建议您不要在开始时使用 typescript,因为您将很难找到使用 typescript 的演示和示例。由于 TypeScript 是 Javascript 的一个子集,所以先学习 javascript 部分

标签: javascript jquery angularjs typescript


【解决方案1】:

您想对如何专门使用 Angular 进行 oauth 进行一些研究。输入 Google 'angular oauth' 应该是一个很好的起点。第一个结果应该是本教程。

http://devcenter.kinvey.com/angular/tutorials/how-to-implement-safe-signin-via-oauth

假设有人已经实现了 oauth 并将其作为维护模块提供是安全的。最好寻找这样的模块。

https://www.google.ie/search?site=&source=hp&ei=IPWWVOqZEePe7AbI8YH4Dg&q=angularjs+oauth+module&oq=angularjs+oauth+module&gs_l=mobile-gws-hp.12...2447.2447.0.3443.2.2.0.1.1.0.203.406.2-2.2.0.msedr...0...1c.2.60.mobile-gws-hp..1.1.88.3.KF2tzFFu2RI

编辑具体到如何使用 TypeScript 和 Angular 调用异步端点:

不要在 Angular 中使用 jQuery。如果您是 JavaScript 新手并且没有使用过 jQuery,最好不要将它与 Angular 一起使用。 jQuery 很棒。但如果你正在学习 Angular,最好不要使用它。

Angular 中的控制器和服务是原型构造函数。这些在 TypeScript 中表示为类。您在 Angular 中使用 service() 方法注册的任何类或原型构造函数都会自动注册为单例

例子

// this is a ts module
// we put our code in here to not polute global scope
// angular modules are different -- don't confuse them
module app {

    // we export the class so that we can access its API from
    // tests. We don't ever want to directly new it from tests though.
    // we should always use $injector.get('myService') to get the test instance.
    export class MyService {

        // We need to tell angular what service to inject.
        // Using the $inject annotation is the cleanest way.
        // Our $inject and constructor are on top of each other
        // this way. We can see that they match
        // As well, we use the type ng.IHttpService with on $http 
        static $inject = ['$http']; 
        constructor(private $http: ng.IHttpService) {}

            getMyEndpoint() {

                return this.$http.get('http://myendpoint.com/myendpoint');

            }
    }

    // here we register this class as a singleton by using the
    // .singleton method. 
    angular.module('app').service('myService', MyService);
}

对于控制器来说也是类似的。对于这个例子,我们将引入我们刚刚创建的单例服务。

module app {

    export class MyController {

        data: MyData[];

        static $inject = ['myService'];
        constructor(myService: MyService) {

            myService.getMyEndpoint().then(
                 (data) => {
                     this.data = data;
                 }
            );
        }

    }
    angular.module('app').controller('MyController', MyController);
}

请注意,我们没有将 $scope 传递给控制器​​。相反,我们将服务调用的结果放在类的公共成员上。然后我们可以使用 controllerAs 语法在视图中访问它。这比将 $scopes 传递到控制器并绑定到它们更可取,因为它们受到范围继承的影响。它们具有与全局作用域相同的缺点。您最终会遇到范围冲突。阅读 controllerAs 语法。

你会注意到我们使用 pascal-case MyController 来注册控制器和 camel-case myServcie 来注册服务。这是为了区分当一个类注册为控制器时,每次检索它时都会返回一个它的新实例。服务是单例的。它仅由 Angular 更新一次。只返回一个实例。

因为我们导出类 API 以用于测试(但不会在测试中或我们应用程序的任何地方更新),我们希望在构建时将我们的应用程序包装在一个闭包中。 Uglifyjs 可以为我们做到这一点。

最后,谷歌“basarat angular typescript”阅读和观看来自@basarat 的许多关于 angular 和 typescript 的教程。

【讨论】:

  • 我确信这些都是很好的参考,但 OP 的问题根本不是关于 OAuth。
  • OP 正在尝试完成 OAuth。最好看看这是如何使用 Angular 完成的,而不是告诉 OP 只使用 $httpservice。
  • 感谢您的回答,但我想要更多关于如何使用 Angular 和 Typescript 的建议,而不是专门针对 oAuth 提供帮助。我确信有一个可用的模块,但我将此作为学习经验来适应一些新技术。我以前用其他语言实现过 OAuth,所以这是一个很好的学习方式。
  • 针对您的问题,TypeScript 是 Javascript 的超集。因此,使用 $http 服务不需要任何特定的打字稿。您确实要确保项目中有 angular.d.ts 类型定义,以便可以在注入中使用 ng.IHttpService 接口。使用 TS,您应该将控制器和服务定义为类。如果我使用计算机,我会尝试用示例更新我的原始答案。
  • 非常感谢。我计划稍后再了解 Angular 的依赖注入位,但似乎很难使用其中的任何一个而不全力以赴。我熟悉 IOC 和构造函数注入,因为我在日常工作中使用 Parsley 和 Flex。跨度>
【解决方案2】:

有一个例子,我如何创建服务:

module MyApp.MyModule
{
    export class SecuritySvc
    {
        private root : string;

        static $inject = ["$http"];

        constructor(private $http: ng.IHttpService)
        {
            this.root = "api/";
        }

        public getRoles()
        : ng.IHttpPromise<IRole[]>
        {
            var url = this.root + "Security/Roles";
            return this.$http.get(url, { withCredentials: true });
        }
        ...
        // many others
    }
}

这样我们就可以将它注入到 Angular 中

angular.module("MyApp.MyModule")
    .service("SecuritySvc", MyApp.MyModule.SecuritySvc)

然后像这样使用它,例如在 my 控制器中

module MyApp.MyModule
{
    export interface IMyScope extends ng.IScope
    {
        Roles:  IRole[];
    }

    export class MyCtrl
    {
        static $inject = ['$scope', "SecuritySvc", ...];

        constructor(public $scope: ng.IRootScopeService
                  , public SecuritySvc: SecuritySvc
                  , ... )
        {
            SecuritySvc
                .getRoles()
                .then((response: ng.IHttpPromiseCallbackArg<IRole[]>) =>
                {
                    var roles = response.data;
                    this.$scope.Roles = roles;
                    ...

控制器是这样定义的:

angular.module('MyApp.MyModule')
    .controller('MyCtrl', MyApp.MyModule.MyCtrl); 

【讨论】:

  • 非常感谢。我希望我可以将两者都标记为答案,但另一张海报会更详细一些并首先回答。
  • 如你所愿。我的答案从一开始就完整,而另一个后来基于我的扩展......无论如何祝你好运Typescript。这是要走的路。
猜你喜欢
  • 2020-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 2017-07-05
  • 2020-03-16
相关资源
最近更新 更多