Angular 如何编写发出http请求并返回请求结果的函数?

Angular 如何编写发出http请求并返回请求结果的函数?,angular,typescript,oop,singleton,Angular,Typescript,Oop,Singleton,函数getEventId()正在返回this.eventId 如果this.eventId==null 正在调用发出http请求的函数 this.eventId=resp(来自请求的响应) 恩戈尼尼特(){ //下面的函数发出http请求。 this.getCustomerFileByCode().subscribe(数据=>{ //从服务器获取Id this.eventId=数据[0]; }) } getEventId(){ if(this.eventId){//如果服务器请求返回的是已存在

函数
getEventId()
正在返回
this.eventId

如果
this.eventId==null

  • 正在调用发出http请求的函数

  • this.eventId=resp
    (来自请求的响应)

    恩戈尼尼特(){ //下面的函数发出http请求。 this.getCustomerFileByCode().subscribe(数据=>{ //从服务器获取Id this.eventId=数据[0]; }) }

    getEventId(){ if(this.eventId){//如果服务器请求返回的是已存在的响应 返回(this.eventId) }否则{ getCustomerFileByCode().subscrive(数据=>{ this.eventId=数据[0] }) //等待服务器响应并返回值 返回此.eventId; }) } }

    getCustomerFileByCode():可观察{ 返回this.http.post(this.\uURL、JSON.stringify(params)、this.options) }


  • 如何在函数
    getEventId()
    中从http请求返回值?

    我想您需要执行类似的操作

    getEventId(elementId):Observable<any> {
        if (this.eventId) { //if the server request returned already 
            return of(this.eventId)
        } else {
            return this.getCustomerFileByCode(elementId).pipe(
             map(data=>data[0]),
             tap(res => { 
                this.eventId = res;
            })
        }
    

    如果“this.eventId”仍然是可观察的,请查看getEventId返回一个可观察的,只需返回,否则调用API,使用map转换响应,并使用tap存储值。当然,由于所有的可观察对象都需要订阅“launch”。嗯,你可以在subscribe中使用相等的值,而不用“tap”。但一般来说,必须在服务中声明可观察对象并在组件中订阅,因此变量“属于”服务更符合逻辑。

    当您实际调用
    this时。_customerService.EventId()来自另一个服务的行..?嘿,我添加了缺少的函数,以便您可以更清楚地理解代码@ganesh045这是
    getCustomerFileByCode()
    使用eventId..?不,它返回的是包含eventId的响应@Ganesh045创建一个主题。当响应到达时,对主题调用next()。然后,在任何你对这些数据感兴趣的地方,观察这个主题。最终,我甚至没有使用
    ngOnInit()
    函数,只是使用了getEventId(),就是这样。这正是我要找的!谢谢大家!@埃利塞
        this.getEventId(this.elementId).subscribe(()=> { 
              ...make something more...
              ...don't worry about this.eventId because the "tap" ...
              ...on the observable yet store the value...
        })