GET и PUT запрос flatMap не возвращает результатов - PullRequest
0 голосов
/ 01 ноября 2019

У меня есть функция getUserInfo, которая может успешно возвращать идентификатор пользователя, адрес электронной почты и т. Д. У меня также есть функция updateUserEmail, которая использует flatMap для консолидации запроса GET (getUserInfo ()) для проверки сервера, а затемPUT запрос. Я никогда не использовал flatMap прежде, поэтому я также пытаюсь выяснить, где сделать проверку. Я не уверен, что я делаю проверку для функции get UserInfo, но это кажется самым логичным местом. Мне нужно проверить запрос GET до запроса PUT в случае сбоя проверки, и я хочу, чтобы запрос PUT не выполнялся.

Также я знаю, что не использую значение userInfo из flatMap. Это потому, что я не совсем уверен, как это сделать. Это не ответ сервера, где я могу получить userInfo._id. Я довольно новичок во всем этом, поэтому спасибо за любую помощь.

пользовательский сервис

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UserEmailChange } from './emailChange.model';
import { flatMap } from 'rxjs/operators';
import { AuthService } from '../auth.service';
import { tap } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class ProfileService {
  userId = localStorage.getItem("userId: ");

  constructor(private http: HttpClient, private authService: AuthService) { }

  getUserInfo(id: string, oldEmail: string) {

    this.http.get(`http://localhost:3000/api/user/${id}`).pipe(tap(value => 'output: ' + "TEST" + value)).subscribe((res) => {


      if (this.userId === res["posts"]._id && oldEmail === res["posts"].email) {
        console.log("You passed the id and email test");
      }
      else {
        console.log("You failed the test!");
      }
    });

    }

    updateUserEmail(emailChange: UserEmailChange) {
      return this.getUserInfo(this.userId, emailChange.oldEmail)
      .pipe(flatMap(userInfo => this.http.put(`http://localhost:3000/api/user/${this.userId}`, emailChange )));
    }

}

пользовательский компонент

import { Component, OnInit } from '@angular/core';
import { ProfileService } from './profile.service';
import { AuthService } from '../auth.service';
import { UserEmailChange } from './emailChange.model';

@Component({
  selector: 'app-profile',
  templateUrl: './profile.component.html',
  styleUrls: ['./profile.component.css']
})
export class ProfileComponent implements OnInit {
  userId: string;
  authenticated = false;
  emailResponse: string;
  idResponse: string;
  oldEmail: string;
  constructor(private profileService: ProfileService, private authService: AuthService) { }

  ngOnInit() {
    this.userId = localStorage.getItem("userId: ");
  }

  onUpdateUserEmail(oldEmail: string, newEmail: string) {
    const userEmailChange = new UserEmailChange();
    userEmailChange.oldEmail = oldEmail;
    userEmailChange.newEmail = newEmail;


    this.profileService.updateUserEmail(userEmailChange).subscribe(emailUpdated => {



    });

  }


}

В настоящее время в updateUserEmail () в службе, .pipe возвращает ошибку Property 'pipe' does not exist on type 'void'.ts

1 Ответ

0 голосов
/ 01 ноября 2019

Как упоминает @Alexander, вы неправильно возвращаете значение из getUserInfo. Вам нужно вернуть наблюдаемое, а затем сделать то, что вам нужно с ним, в функции, которую вы возвращаете в

getUserInfo(id: string, oldEmail: string) {
  return this.http.get(`http://localhost:3000/api/user/${id}`)
                  .pipe(
                    tap(value => 'output: ' + "TEST" + value),
                    tap(res => {
                      if (this.userId === res["posts"]._id && oldEmail === res["posts"].email)
                        console.log("You passed the id and email test");
                      else console.log("You failed the test!");
                    })
                  );
}

updateUserEmail(emailChange: UserEmailChange) {
  return this.getUserInfo(this.userId, emailChange.oldEmail)
             .pipe(
                flatMap(userInfo => this.http.put(`http://localhost:3000/api/user/${this.userId}`, emailChange))
             );
}
...