Angular 服务未执行 switchmap

Angular Service not executing switchmap

我有一个无法进入的开关图。我今天早些时候让它工作,但由于某种原因现在它没有输出 alert("INSIDE SWITCHMAP") 或 switchmap 中的 console.logs。

还有这个小块警报

    alert(userId);
    alert(currentPage);
    alert(auctionId);

输出正确的值,因此 none 个值为空。

有什么建议吗?感谢您的帮助!

import { Injectable, OnDestroy } from "@angular/core";
import { HttpClient, HttpParams } from "@angular/common/http";
import { Router } from "@angular/router";
import { Subject } from "rxjs";
import { Bidding } from "./bidding.model";
import { Watching } from "../watching/watching.model";
import { PasswordReset } from "../reset-password/password.model";
import { environment } from 'src/environments/environment';
import { takeUntil, switchMap } from 'rxjs/operators';

@Injectable({ providedIn: "root" })
export class BiddingService implements OnDestroy {
  destroy = new Subject();
  constructor(private http: HttpClient, private router: Router) { }

  submitBid(
    auctionId: string,
    currentBid: string,
    userId: string,
    biddingGroup: string[],
    auctionEndDateTime: string,
    lastBidderName: string,
    runnerUpBidderName: string,
    runnerUpBid: string,
    reservePriceBeat: boolean,
    currentPage: string
  ) {

    let bidderName;
    let listingHasBeenFound = false;

    const bidding: Bidding = {
      id: auctionId,
      bidderId: userId,
      lastBidTimeStamp: null,
      currentBid: currentBid,
      runnerUpBidderName: runnerUpBidderName,
      runnerUpBid: runnerUpBid,
      lastBidderName: lastBidderName,
      biddingGroup: biddingGroup,
      auctionEndDateTime: auctionEndDateTime,
      reservePriceBeat: reservePriceBeat
    };

    alert("OUTSIDE SWITCHMAP")
    alert(userId);
    alert(currentPage);
    alert(auctionId);

    return this.getUserNameandListingPage(userId, currentPage, auctionId).pipe(
      switchMap(res => {
        alert("INSIDE SWITCHMAP")
        bidderName = res.posts.username;
        listingHasBeenFound = res.listingHasBeenFound;
        console.log("bidderName");
        console.log(bidderName);
        console.log(listingHasBeenFound);

        console.log(res);

        return this.http.patch(
          environment.api_url + `/listings/${bidding.id}`,
          bidding
        );
      })
    );

  }



  getUserNameandListingPage(id: string, currentPage: string, listingId: string) {


    const params = new HttpParams()
      .set("userIdBidder", id)
      .set("listingId", listingId)
      .set("currentPage", currentPage);

    return this.http.get<{ posts: any; listingHasBeenFound: boolean }>(
      environment.api_url + `/user/${id}`, { params }
    );
  }



  ngOnDestroy() {
    this.destroy.next();
    this.destroy.complete();
  }

}

confirmBid 组件

import {
  Component,
  Output,
  EventEmitter,
  Inject,
  OnInit,
  OnDestroy
} from "@angular/core";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material";
import { AuctionListingsComponent } from "../auction-listings/auction-listings.component";
import { BiddingService } from "../auction-listings/bidding.service";
import { ToastrService } from "ngx-toastr";
import * as Ably from "ably";
import { SubmitListingService } from "../submit-listing/submit-auction.service";
import { Subject } from "rxjs";
import { startWith, filter, takeUntil } from "rxjs/operators";
let api = process.env.ablyAPi;
let options: Ably.Types.ClientOptions = { key: api };
let client = new Ably.Realtime(options); /* inferred type Ably.Realtime */
let channel = client.channels.get(
  "auctions"
); /* inferred type Ably.Types.RealtimeChannel */

@Component({
  selector: "app-confirmation-dialog",
  templateUrl: "./confirmation-dialog.component.html",
  styleUrls: ["./confirmation-dialog.component.css"]
})
export class ConfirmationDialogComponent implements OnInit, OnDestroy {
  currentBid: string;
  bidInput: string;
  auctionId: string;
  userId: string;
  runnerUpBidderName: string;
  runnerUpBid: string;
  bidderName: string;
  biddingGroup: string[];
  currentData: any[];
  auctionEndDateTime: string;
  currentPage: string;
  success: boolean;
  listingHasBeenFound: boolean;
  username: string;
  reservePriceBeat = false;
  destroy = new Subject();

  constructor(
    public dialogRef: MatDialogRef<AuctionListingsComponent>,
    @Inject(MAT_DIALOG_DATA) public data: ConfirmationDialogComponent,
    private biddingService: BiddingService,
    private toastr: ToastrService,
    private submitListingService: SubmitListingService
  ) { }

  ngOnInit() {
    this.auctionId = this.data.auctionId;
    this.runnerUpBid = this.data.currentBid;
    this.bidInput = this.data.bidInput;
    this.userId = this.data.userId;
    this.runnerUpBidderName = this.data.runnerUpBidderName;
    this.biddingGroup = this.data.biddingGroup;
    this.currentPage = this.data.currentPage;
    this.reservePriceBeat = this.data.reservePriceBeat;
    this.auctionEndDateTime = this.data.auctionEndDateTime;
    this.listingHasBeenFound = this.data.listingHasBeenFound;
    this.bidderName = this.data.bidderName;

  }

  ngOnDestroy() {
    this.destroy.next();
    this.destroy.complete();
  }

  confirmBid() {
    const data = {
      auctionId: this.auctionId,
      lastBid: this.bidInput,
      lastBidderId: this.userId,
      username: this.username
    };
    // Optionally, you can use a callback to be notified of success or failure
    channel.publish("auctions", data);
    this.biddingService
      .submitBid(
        this.auctionId,
        this.bidInput,
        this.userId,
        this.biddingGroup,
        this.auctionEndDateTime,
        this.username,
        this.runnerUpBidderName,
        this.runnerUpBid,
        this.reservePriceBeat,
        this.currentPage
      )
      .pipe(takeUntil(this.destroy))
      .subscribe(res => {
        console.log("RES");
        console.log(res);
      });

    this.toastr.success("Your bid has been submitted", "", {
      timeOut: 2000
    });

    this.success = true;

    var returnData = [
      {
        newEndTime: this.auctionEndDateTime,
        auctionId: this.auctionId,
        success: this.success,
        username: this.username
      }
    ];

    this.dialogRef.close(returnData);
  }

  cancel() {

    this.dialogRef.close(true);
    this.success = false;
  }
}

api 通话

if (req.query.userIdBidder) {
    console.log("correct path!");
    console.log(req.query.userIdBidder);

    Post.find({
      $and: [
        { auctionType: { $eq: "publicAuction" } },
        { auctionEndDateTime: { $gte: Date.now() } },
        { blacklistGroup: { $ne: req.query.bidderUserId } },
        // { startTime: { $lte: Date.now() } }
      ]
    }) //test
      .skip(10 * (req.query.currentPage - 1))
      .sort({ dateCreated: -1 })
      .limit(10)
      .then(listings => {

        console.log("listings");

        let listingHasBeenFound = false;
        for (let i = 0; i < listings.length; i++) {

          console.log("i");
          console.log(i);
          console.log(req.query.listingId);
          console.log(listings[i]._id);
          if (listings[i]._id.toString().trim() === req.query.listingId.toString().trim()) {
            listingHasBeenFound = true;
            break;
          }

        }

        console.log("CURRENT PAGE " + req.query.listingId);


        User.findById({ _id: req.query.userIdBidder })
          .select("username")
          .then(documents => {
            console.log("HERE WE ARE")
            res.status(200).json({
              message: "User account located!",
              posts: documents,
              listingHasBeenFound: listingHasBeenFound
            });
          });
      }).catch((res) => {

        console.log("ERROR");
        console.log(res);
      });

  }

稍微修改一下 ConfirmationDialogComponent 中的 confirmBid() 方法(将结束 subscribe 圆括号后的所有代码移至订阅者函数内):

confirmBid() {
    const data = {
      auctionId: this.auctionId,
      lastBid: this.bidInput,
      lastBidderId: this.userId,
      username: this.username
    };
    // Optionally, you can use a callback to be notified of success or failure
    channel.publish("auctions", data);
    this.biddingService
      .submitBid(
        this.auctionId,
        this.bidInput,
        this.userId,
        this.biddingGroup,
        this.auctionEndDateTime,
        this.username,
        this.runnerUpBidderName,
        this.runnerUpBid,
        this.reservePriceBeat,
        this.currentPage
      )
      .pipe(takeUntil(this.destroy))
      .subscribe(res => {
          this.toastr.success("Your bid has been submitted", "", {
            timeOut: 2000
          });

          this.success = true;

          const returnData = [{
              newEndTime: this.auctionEndDateTime,
              auctionId: this.auctionId,
              success: this.success,
              username: this.username
          }];

          this.dialogRef.close(returnData);
      });
  }