GVKun编程网logo

angularjs – Angular Http – toPromise或subscribe(angular.js)

13

对于想了解angularjs–AngularHttp–toPromise或subscribe的读者,本文将是一篇不可错过的文章,我们将详细介绍angular.js,并且为您提供关于Angular8>我

对于想了解angularjs – Angular Http – toPromise或subscribe的读者,本文将是一篇不可错过的文章,我们将详细介绍angular.js,并且为您提供关于Angular 8>我从Http.Subscribe正确获取数据,但是未定义、angular min js 118 Error ng areq http //errors angularjs、Angular NgUpgrade将AngularJS服务注入Angular服务;获取:未处理的Promise拒绝:无法读取未定义的属性’get’;区:、angular – http提供程序Observable.toPromise()在promise链中没有按预期工作的有价值信息。

本文目录一览:

angularjs – Angular Http – toPromise或subscribe(angular.js)

angularjs – Angular Http – toPromise或subscribe(angular.js)

我在Angular上观看了一些课程,发现有不同的方法来管理来自Http请求的数据.

>使用Observables,.map(),. sububscribe()
>使用Promises,.toPromise(),. then(),. catch()

我在我的应用程序中使用了toPromise(),因为我发现它类似于AngularJS Http服务.

在什么情况下我需要使用Observables?

解决方法

如果您喜欢反应式编程风格并希望在应用程序中保持一致,即使对于单个事件(而不是事件流)也始终使用observable,然后使用observables.如果这对您无关紧要,请使用toPromise().

可观察的一个优点是,您可以取消该请求.

另见Angular – Promise vs Observable

Angular 8>我从Http.Subscribe正确获取数据,但是未定义

Angular 8>我从Http.Subscribe正确获取数据,但是未定义

您可以在内部调用您的方法来订阅以执行加载数据后想要做的事情:

Playground link

type Email<T extends string> = T &
  CheckMaxLength<T,32,RestrictedToChars<
    `${lowercase T}`,AllowedChars,T,["Email can only contain alphabet or @ or ."]
  >,["Email needs to be 32 characters or less"]>;

type User<T extends string> = {
  name: string;
  email: Email<T>;
}

或返回可以订阅的任何地方使用结果:

Angular 2+ wait for subscribe to finish to update/access variable

const user = <T extends string>(user: User<T>) => user;

user({ name: "Dave Morrison",email: "Dave.Morrison@gmail.com" }); // okay
user({ name: "Van Morrison",email: "Van-Morrison@gmail.com" }); // error!
// ------------------------> ~~~~~
// '["Email can only contain alphabet or @ or ."]'
user({ name: "Jim Morrison",email: "Jim.Morrison.is.my.name.and.it.is.too.long@gmail.com" }); // error!
// ------------------------> ~~~~~
// '["Email needs to be 32 characters or less"]'

在您设置的方法中

 export class myClass {
  myVariable: any;

  myFunction() {
    this.myService.getApi().subscribe(data => {
      this.myVariable = data;
      this.update()
    });

    this.update()
  }

  update(){
    console.log(this.myVariable);
  }
}

或者使用await等到结果准备好:

Angular 6 wait for subscribe to finish

getNumber(value) {
    return this.myService.getApi(value).pipe(tap(data => {
        this.myVariable = data;
    }));
}
,

您将变得不确定,因为它是一个异步方法,不会等待从服务器获得响应。 尝试使用async / await或在其中打印值然后阻止

    this.http.get<Reserve[]>(this.url).subscribe(result => {
        this.reserves = result;
        console.log('Data from source:',result,'Data when load:',this.reserves)
        console.log('Data after Load',this.reserves);
    },error => console.error('Loading reserve error',error));

angular min js 118 Error ng areq http //errors angularjs

angular min js 118 Error ng areq http //errors angularjs

1、错误描述

 

angular.min.js:118 Error: [ng:areq] http://errors.angularjs.org/1.5.8/ng/areq?p0=username&p1=not%20a%20function%2C%20got%20undefined
    at Error (native)
    at http://127.0.0.1:8020/AngularJS/js/angular.min.js:6:412
    at sb (http://127.0.0.1:8020/AngularJS/js/angular.min.js:23:18)
    at Pa (http://127.0.0.1:8020/AngularJS/js/angular.min.js:23:105)
    at http://127.0.0.1:8020/AngularJS/js/angular.min.js:89:310
    at ag (http://127.0.0.1:8020/AngularJS/js/angular.min.js:72:419)
    at p (http://127.0.0.1:8020/AngularJS/js/angular.min.js:64:262)
    at g (http://127.0.0.1:8020/AngularJS/js/angular.min.js:58:481)
    at g (http://127.0.0.1:8020/AngularJS/js/angular.min.js:58:498)
    at g (http://127.0.0.1:8020/AngularJS/js/angular.min.js:58:498)

 

分享图片


2、错误原因

 

<!DOCTYPE html>
<html ng-app>
	<head>
		<Meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/angular.min.js" ></script>
	</head>
	<body>
		<div ng-controller="username">
			<input type="text" id="inp" ng-model="user.name">
			<div>{{user.name}}</div>
		</div>
		<script> function username($scope) { $scope.user = {name:"张丝丝"}; } </script>
	</body>
</html>


 

3、解决办法

<!DOCTYPE html>
<html ng-app="userApp">
	<head>
		<Meta charset="UTF-8">
		<title></title>
		<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
		<script> var app = angular.module("userApp",[]); app.controller("username",function($scope){ $scope.user = {name:"张丝丝"} }); </script>
	</head>
	<body>
		<div ng-controller="username">  
            <input type="text" id="inp" ng-model="user.name">  
            <div>{{user.name}}</div>  
        </div>  
	</body>
</html>

分享图片



 

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

Angular NgUpgrade将AngularJS服务注入Angular服务;获取:未处理的Promise拒绝:无法读取未定义的属性’get’;区:

Angular NgUpgrade将AngularJS服务注入Angular服务;获取:未处理的Promise拒绝:无法读取未定义的属性’get’;区:

我在这里看到了很多类似的问题,但还没有找到一个有效的解决方案.我认为正在发生的是,因为我们的Ng2App首先被引导,它还没有引用$injector,所以当我尝试在我的提供者声明(deps:[‘$injector’])中使用它时,它没有’存在.

什么是INSANELY奇怪的是我可以在Angular COMPONENT中使用此服务但由于某种原因无法在Angular SERVICE中使用它.

app.js

import UserService from './user.service';
angular.module('app',[])
  .service('UserService',UserService)
  .config(/* config */)
  .run(/* run */);

 import './ng2app.module';

ng2app.module.ts:

import { browserModule } from '@angular/platform-browser';
import { UpgradeModule } from '@angular/upgrade/static';
import { platformbrowserDynamic } from '@angular/platform-browser-dynamic';
@NgModule({
  imports: [
    browserModule,UpgradeModule,],declarations: [],entryComponents: [],providers: [
    // angularJS service:
    { 
     provide: 'UserService',useFactory: (i: any) => i.get('UserService'),// <---- this is the line all the errors point to.
     deps: ['$injector']
    },]
})
export default class Ng2AppModule {
  constructor(){}
}


platformbrowserDynamic()
  .bootstrapModule(Ng2AppModule)
  .then(platformRef => {
    const upgrade = platformRef.injector.get(UpgradeModule) as UpgradeModule;
    upgrade.bootstrap(document.documentElement,['app'],{strictDi: true});
});

后来…在服务中(失败):

import {Injectable,Inject} from "@angular/core";
import UserService from 'app/login/user.service';

@Injectable()
export class AnAngularservice{
  constructor(
    // causes the error if I uncomment it wtf: <--------------
    // @Inject('UserService') private userService: UserService
  ){}
}

稍后……在一个组件中(正常工作):

import { Component } from '@angular/core';
import {Inject} from "@angular/core";
import UserService from 'app/login/user.service';
import template from 'tmpl.html';

@Component({
  selector: 'an-angular-component',template,})
export class AnAngularComponent{
  constructor(

    @Inject('UserService') private userService: UserService
  ){
    console.log(userService) // works just fine. wtf <--------------
  }
}

有谁知道为什么会这样,以及如何解决它?

This question is almost exactly the same thing but for some reason it didnt work

AngularJS版本:1.5.8
角/核心等版本:4.2.4

Here’s a link to the Github issue I opened in the Angular repo

堆栈跟踪:

zone.js:522 Unhandled Promise rejection: Cannot read property 'get' of undefined ; Zone: <root> ; Task: Promise.then ; Value: TypeError: Cannot read property 'get' of undefined
    at useFactory (ng2app.module.ts:114)
    at _callFactory (core.es5.js:9604)
    at _createProviderInstance$1 (core.es5.js:9547)
    at initNgModule (core.es5.js:9498)
    at new NgModuleRef_ (core.es5.js:10606)
    at createNgModuleRef (core.es5.js:10590)
    at Object.debugCreateNgModuleRef [as createNgModuleRef] (core.es5.js:12874)
    at NgModuleFactory_.create (core.es5.js:13869)
    at core.es5.js:4556
    at ZoneDelegate.invoke (zone.js:334)
    at Object.onInvoke (core.es5.js:3933)
    at ZoneDelegate.invoke (zone.js:333)
    at Zone.run (zone.js:126)
    at ngzone.run (core.es5.js:3801)
    at PlatformRef_._bootstrapModuleFactoryWithZone (core.es5.js:4554)
    at core.es5.js:4596
    at ZoneDelegate.invoke (zone.js:334)
    at Zone.run (zone.js:126)
    at zone.js:713
    at ZoneDelegate.invokeTask (zone.js:367)
    at Zone.runTask (zone.js:166)
    at drainMicroTaskQueue (zone.js:546)
    at <anonymous> TypeError: Cannot read property 'get' of undefined
    at useFactory (http://localhost:9000/app.bundle.js:4404:52)
    at _callFactory (http://localhost:9000/vendor.bundle.js:10600:26)
    at _createProviderInstance$1 (http://localhost:9000/vendor.bundle.js:10543:26)
    at initNgModule (http://localhost:9000/vendor.bundle.js:10494:13)
    at new NgModuleRef_ (http://localhost:9000/vendor.bundle.js:11602:9)
    at createNgModuleRef (http://localhost:9000/vendor.bundle.js:11586:12)
    at Object.debugCreateNgModuleRef [as createNgModuleRef] (http://localhost:9000/vendor.bundle.js:13870:12)
    at NgModuleFactory_.create (http://localhost:9000/vendor.bundle.js:14865:25)
    at http://localhost:9000/vendor.bundle.js:5552:61
    at ZoneDelegate.invoke (http://localhost:9000/vendor.bundle.js:289131:26)
    at Object.onInvoke (http://localhost:9000/vendor.bundle.js:4929:37)
    at ZoneDelegate.invoke (http://localhost:9000/vendor.bundle.js:289130:32)
    at Zone.run (http://localhost:9000/vendor.bundle.js:288923:43)
    at ngzone.run (http://localhost:9000/vendor.bundle.js:4797:62)
    at PlatformRef_._bootstrapModuleFactoryWithZone (http://localhost:9000/vendor.bundle.js:5550:23)
    at http://localhost:9000/vendor.bundle.js:5592:59
    at ZoneDelegate.invoke (http://localhost:9000/vendor.bundle.js:289131:26)
    at Zone.run (http://localhost:9000/vendor.bundle.js:288923:43)
    at http://localhost:9000/vendor.bundle.js:289510:57
    at ZoneDelegate.invokeTask (http://localhost:9000/vendor.bundle.js:289164:31)
    at Zone.runTask (http://localhost:9000/vendor.bundle.js:288963:47)
    at drainMicroTaskQueue (http://localhost:9000/vendor.bundle.js:289343:35)
    at <anonymous>
consoleError @ zone.js:522
handleUnhandledRejection @ zone.js:527
_loop_1 @ zone.js:562
drainMicroTaskQueue @ zone.js:566
Promise resolved (async)
scheduleQueueDrain @ zone.js:505
scheduleMicroTask @ zone.js:513
ZoneDelegate.scheduleTask @ zone.js:356
Zone.scheduleTask @ zone.js:196
Zone.scheduleMicroTask @ zone.js:207
scheduleResolveOrReject @ zone.js:711
ZoneAwarePromise.then @ zone.js:800
PlatformRef_._bootstrapModuleWithZone @ core.es5.js:4596
PlatformRef_.bootstrapModule @ core.es5.js:4581
(anonymous) @ ng2app.module.ts:140
__webpack_require__ @ bootstrap 2f644bad14cb0bb324ab:691
fn @ bootstrap 2f644bad14cb0bb324ab:110
(anonymous) @ app.js:116
__webpack_require__ @ bootstrap 2f644bad14cb0bb324ab:691
fn @ bootstrap 2f644bad14cb0bb324ab:110
(anonymous) @ util (ignored):1
__webpack_require__ @ bootstrap 2f644bad14cb0bb324ab:691
webpackJsonpCallback @ bootstrap 2f644bad14cb0bb324ab:23
(anonymous) @ app.bundle.js:1

解决方法

这似乎是调整@NgModule({providers:[]})和upgrade.bootstrap解决方案的问题.

在这里你需要$injector,但它在被请求时没有被注入.

在docs中它说你应该使用ngdobootstrap钩子.

export function userServiceFactory(i: any) {
  return i.get('UserService');
}

export const userServiceProvider = {
  provide: 'UserService',useFactory: userServiceFactory,deps: ['$injector']
};

import { browserModule } from '@angular/platform-browser';
import { UpgradeModule } from '@angular/upgrade/static';
import { platformbrowserDynamic } from '@angular/platform-browser-dynamic';
@NgModule({
  imports: [
    browserModule,providers: [
     userServiceProvider
  ]
}) 


export default class Ng2AppModule {

   constructor(private upgrade: UpgradeModule) { }

   ngdobootstrap() {
     this.upgrade.bootstrap(document.body,{ strictDi: true });
   }
}

platformbrowserDynamic().bootstrapModule(Ng2AppModule);

由安德鲁·卢林编辑为后代
不幸的是,即使这正是在角度文档中写的正是如此.这里的原始答案是:

import { forwardRef } from '@angular/core';

useFactory: (forwardRef(() => '$injector')i: any) => i.get('UserService')

而这似乎比这更接近答案.这也不起作用 – 但这似乎是因为TypeScript不认为语法是正确的.

更新:

我们对useFactory如此着迷,以至于我们没有看到修复只是将forwardRef添加到服务中.

@Injectable()
export class AnAngularservice{
  constructor(@Inject(forwardRef(() => 'UserService')) private userService: UserService
  ){}
}

angular – http提供程序Observable.toPromise()在promise链中没有按预期工作

angular – http提供程序Observable.toPromise()在promise链中没有按预期工作

如果我使用ng2 http提供程序Observable.toPromise()支持调用promise启用方法,它按预期工作,但当我将它作为promise链的一部分使用时,它会在then处理程序处理完并返回结果之前解析返回的promise.

使Observable.toPromise()在promise链中工作的任何已知问题或我可能测试的替代方法使其成为与promise链兼容的结果?在http请求,promise链中的最后一项,已完成其异步请求并返回结果之前,我被此解析承诺阻止.

例如

this.myService.getSomethingInvolvingingMultiplePromiseCalls().then(result => {
    let valueFromSomethingInvolvingMultiplePromiseCalls = result;
},err => { 
    console.error('landed in app.component outer promise rejected handler,see output window for details')
})

public getSomethingInvolvingingMultiplePromiseCalls(): Promise<string> {
    return this.getSomethingInvolvingPromiseCall().then(resultPromise1 => {
        let resultPromise1propertyFoo = resultPromise1.propertyFoo;
            return this.getSomethingInvolvingNg2HttpProviderToPromiseCall(resultPromise1propertyFoo);
        }
        .then(resultPromise2 => {
            let resultPromise2propertyBar = resultPromise2.propertyBar;
            return resultPromise2propertyBar;
        }   
    }

getSomethingInvolvingNg2HttpProviderToPromiseCall(arg1: string): Promise<string> {
   let body = 'some body content Leveraging arg1';
   let headers = new Headers({ 'Authorization': 'Bearer ' + accesstoken,'Content-Type': 'application/x-www-form-urlencoded' });
   let options = new RequestOptions({ headers: headers });

   return this.http.post(resourceBaseAddress + '/someRestApi',body,options).toPromise().then(response => {
        let responseJson = response.json();
        return responseJson['someJsonProperty'];
      });
    }
}

提前感谢任何见解或建议.

解决方法

我找到了解决方法.

它涉及创建和返回一个typescript延迟的promise,我控制解析只有在我使用angular2 http provider toPromise()调用then方法调用方法时才解析.

我没有与其他承诺链接方案有什么关系,但无论出于何种原因,在这种情况下允许停放方法调用方,直到完成链中的http提供者toPromise()调用.

public getSomethingInvolvingingMultiplePromiseCalls(): Promise<string> {
    let resolveFn,rejectFn;
    let promise = new Promise((resolve,reject) => { resolveFn = resolve; rejectFn = reject; });

    this.getSomethingInvolvingPromiseCall().then(resultPromise1 => {
        this.getSomethingInvolvingNg2HttpProviderToPromiseCall(resultPromise1).then(resultPromise2 => resolveFn(resultPromise2));
    }

    return promise;  // return the promise for outside callers to wait on
}

我们今天的关于angularjs – Angular Http – toPromise或subscribeangular.js的分享已经告一段落,感谢您的关注,如果您想了解更多关于Angular 8>我从Http.Subscribe正确获取数据,但是未定义、angular min js 118 Error ng areq http //errors angularjs、Angular NgUpgrade将AngularJS服务注入Angular服务;获取:未处理的Promise拒绝:无法读取未定义的属性’get’;区:、angular – http提供程序Observable.toPromise()在promise链中没有按预期工作的相关信息,请在本站查询。

本文标签: