是否可以从异步上下文访问角度服务?

时间:2019-07-31 17:27:23

标签: angular typescript

因此,我一直在尝试在promise回调中访问我的服务。 我已经添加了所有必要的模块,并将其导入到我的文件中。 我也在构造函数中声明了它们。

//This is part of my login Component Class and this line code is bound to a //button click

clicked(){
this.http.get(..)toPromise().then( this.loginCallbackHandler ).catch((error) => console.log(error));
      //any service accessed here works fine example
      console.log(this.app)// this is fine here
}
//
loginCallbackHandler(reponse){
      //accessing any service from here produces the the error below (error1)
      //For example
      console.log(this.html)
      //Or
      console.log(this.app)
}
//constructor definition
  constructor(@Host() public app: AppComponent,
              private oauthService: OAuthService,
              private http: HttpClient
              ){}

//Error1

ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'html' of undefined
TypeError: Cannot read property 'html' of undefined
    at push../src/app/login/login.page.ts.LoginPage.loginCallbackHandler (login.page.ts:64)
    at 

编辑: 事实证明,这个问题是我对'this'关键字上下文的理解,而不是角度服务。

2 个答案:

答案 0 :(得分:2)

更改此

from jwt import scopes                                                   
from googleapiclient.discovery import build
from google.oauth2 import service_account
import json
import asyncio

key = 'file.json'
ID = 'ID'
rg = 'A1'

j2 = service_account.Credentials.from_service_account_file(key, scopes=scopes).with_subject('me@emial.com')

ar = []
cl = build('classroom', 'v1', credentials=j2)

def cour():
    co = []
    result1 = cl.courses().list().execute()
    courses = result1.get('courses', [])
    for cc in courses:
        co.append(cc['id'])
    return co

cco = cour()

async def main():
    async def subs2(i):
        await asyncio.sleep(0)
        result2 = cl.courses().courseWork().list(courseId=i).execute() 
        works = result2.get('courseWork', [])

        for work in works:
            result = cl.courses().courseWork().studentSubmissions().list(courseId=work['courseId'], courseWorkId=work['id']).execute()
            subs = result.get('studentSubmissions', [])

            for sub in subs:
                try:
                    ar.append(sub['assignedGrade'])
                    ar.append(sub['courseId'])
                    ar.append(sub['courseWorkId'])
                    ar.append(sub['userId'])
                except KeyError as name: 
                    pass

    coros = [subs2(i) for i in cco]
    await asyncio.gather(*coros)

if __name__ == '__main__':
    cour()
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

对此

this.http.get(..)toPromise().then( this.loginCallbackHandler )

clousures没有this.http.get(..)toPromise().then( this.loginCallbackHandler.bind(this) ) 上下文,因此必须将其绑定。

答案 1 :(得分:1)

正如一些评论中已经提到的,this上下文不是您所期望的。使用.bind(this)或使用lambda语法。

clicked() {
   this.http.get(..)
      .toPromise()
      .then(response => this.loginCallbackHandler(response))
      .catch(error => console.log(error));
}

我建议您阅读JavaScript中this上下文的行为(因此在TypeScript中)。 This would be a good start.

另一方面,如果要使用Promise,也可以使用async / await。

async clicked() {
   try {
      const response = await this.http.get(..).toPromise();
      this.loginCallbackHandler(response) ;
   } catch (error) {
      console.log(error);
   } 
}
相关问题