Функция «Отправить приглашение».Я пытаюсь получить строку ввода пользователя (из всплывающего окна), вызвать маршрут Profile в API и вернуть его profileID, чтобы я мог отправить вызов POST в API.Я завершаю это в рамках общей функции "InviteRequests ()", обратите внимание на examplesService.Тем не менее, после подписки данных профиля на глобальную переменную «пригласила пользователя», приглашение всегда остается неопределенным.
Как я могу сделать так, чтобы я подписал данные профиля на 'Inviteuser' и использовал их вне этого сервисного вызова?
Пригласить компонент TS:
export class EventInviteModalComponent implements OnInit {
canModify: boolean;
comments: Comment[];
requests: Request[];
requestInviteControl = new FormControl();
requestFormErrors = {};
isDeleting = false;
public inviteeProfile: Profile;
public requestInvitee: string;
constructor(
private requestsService: RequestsService,
private profilesService: ProfilesService,
private route: ActivatedRoute,
private eventsService: EventsService,
private userService: UserService,
private router: Router
) { }
@Input() event: Event;
@Output() toggle = new EventEmitter<boolean>();
isSubmitting = false;
ngOnInit() {
}
inviteRequest() {
this.isSubmitting = true;
this.route.data.subscribe(
(data: { event: Event }) => {
this.event = data.event;
});
// TODO: remove nested subscribes, use mergeMap
const user = this.userService.getCurrentUser();
const userId = user.id;
this.userService.isAuthenticated.pipe(concatMap(
(authenticated) => {
// Not authenticated? Push to login screen
if (!authenticated) {
this.router.navigateByUrl('/login');
return of(null);
}
this.route.data.subscribe(
(data: { event: Event }) => {
this.event = data.event;
})
this.requestInvitee = this.requestInviteControl.value;
this.profilesService.get(this.requestInviteControl.value).subscribe(
(data: Profile) => {
this.inviteeProfile = data;
this.requestInvitee = this.inviteeProfile.id
console.log("inside function changes username to ID", this.requestInvitee);
})
console.log("here it still remains their username, not ID", this.requestInvitee)
return this.requestsService.invite(this.event.slug, this.requestInvitee)
.pipe(tap(
request => {
this.event.requests.unshift(request);
this.requestInviteControl.reset('');
this.isSubmitting = false;
this.toggle.emit(true);
},
errors => {
this.isSubmitting = false;
this.requestFormErrors = errors;
}
));
}
)).subscribe();
}
}
Как вы можете видеть, я получаю идентификатор пользователя для requestInvitee, где я вызываю profileService, но после закрытия этой функции она просто не используется, а в ответе вместо этого используется строка имени пользователя для запроса приглашения.
Здесьсхема запроса, который я отправляю.«Приглашенный» - это пользователь, которому я тоже отправляю приглашение:
Интерфейс запроса:
import { Profile } from './profile.model';
import { Team } from './team.model';
import { Event } from './event.model';
import { User } from './user.model';
export interface Request {
id: number;
body: string;
points: number;
state: string;
createdAt: string;
author: Profile;
event: Event;
team: Team;
invitee: Profile;
}
А вот вызов, который Служба выполняет с использованием параметров из вышеприведенного TS:
invite(slug, payload): Observable<Request> {
return this.apiService
.post(
`/events/${slug}/requests`,
{ request: { invitee: payload } }
).pipe(map(data => data.requests));
}