Angular-订阅HTTP服务回调

时间:2019-06-14 19:13:43

标签: javascript angular callback

我正在努力理解这一点。

在我的requests.service中,我有一个调用后端的函数:

loginUser(username, pw): Observable <any>{
    const body = {
      username: username,
      password: pw
    }
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", "Basic " + btoa('test:test'));
    headers = headers.append("Content-Type", "application/json");

   return this.http.post('https://website.com/1/user/login', body, {headers: headers})
   .subscribe((data)=>{ //use methods in our service
     console.log(data)
     this.userData = data;
   }, (err)=> console.log(err));
  }

这有效,返回data

现在,在login.page.ts中,我想调用loginUser,但是我也想在其上进行回调,以便知道何时成功运行它,所以我这样做:

this.req.loginUser(info.email, info.password).then((data) => {
  console.log(data)
})

但是我得到了错误:

  

this.req.loginUser(...)。则不是函数

如果我只是console.log而没有回调,它可以正常工作,但是我需要知道呼叫何时成功。

有什么想法吗?

3 个答案:

答案 0 :(得分:2)

这是可观察的回来,而不是诺言。因此.then不适用。

this.req.loginUser(info.email, info.password).pipe().subscribe((data) => {
  console.log(data) // whenever data returns do something with it
})

我们使用pipe()可以对订阅执行更多操作,例如:

.pipe(
   take(1) // will allow the subscription to return 1 time then unsubscribe 
   takeUntil() // subscribe until a condition is met
   map() // map your observable
   etc.
) 

答案 1 :(得分:2)

由于loginUser返回了Observable,因此您需要subscribe

this.req.loginUser(info.email, info.password).subscribe((data) => {
  console.log(data)
})

答案 2 :(得分:2)

您需要像这样更新loginUser,以防您想使用可观察的对象,而无需在loginUser中进行订阅

loginUser(username, pw): Observable <any>{
    const body = {
      username: username,
      password: pw
    }
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", "Basic " + btoa('test:test'));
    headers = headers.append("Content-Type", "application/json");
    const url = 'https://website.com/1/user/login';
   return this.http.post(url, body, {headers: headers}); // ?

  }

调用这样的方法?

this.req.loginUser(info.email, info.password).subscribe((data)=>{ 
         console.log(data);
         this.userData = data;
}, (err)=>{
         console.log(err)
});

如果要使用then方法,并且想每天调用该方法 使用toPromise方法将可观察对象转换为Promise

loginUser(username, pw): Promise <any>{
    const body = {
      username: username,
      password: pw
    }
    let headers = new HttpHeaders();
    headers = headers.append("Authorization", "Basic " + btoa('test:test'));
    headers = headers.append("Content-Type", "application/json");
    const url = 'https://website.com/1/user/login';
   return this.http.post(url, body, {headers: headers}).toPromise(); // ?

  }

现在您可以使用then方法

this.req.loginUser(info.email, info.password).then((data)=>{ 
         console.log(data);
         this.userData = data;
 }).
 catch( err => console.log(err));

??

  

两种方法之间的主要区别(如果可以观察到此?this.req.login User(info.email, info.password))将不会运行,除非您订阅但   在答应的情况下,?this.req.login User(info.email, info.password)   即使不使用也会运行该方法,然后请求将发送到   服务器??