Issue
I want to use the value from user outside subscribe to assign it to my tweet class. How can i do that because if i try to print it outside subscribe it says undefined..
Here is my code ...
entities
export class Tweet {
id: number;
created_at: Date;
message: string;
updated_at: Date;
user: User;
export class User {
id?: number;
username?: string;
password?: string;
email?: string;
imageUrl?: string;
accountType?: string;
}
}
service
export class UserService {
private apiServerUrl: string;
constructor(private http: HttpClient) {
this.apiServerUrl = environment.apiBaseUrl;
}
public findUserById(userId: number): Observable<User> {
return this.http.get<User>(`${this.apiServerUrl}/user/${userId}`);
}
createTweet(tweet: Tweet) : Observable<Tweet> {
return this.http.post<Tweet>(`${this.url}/tweet`, tweet);
}
}
component
user: User = new User();
getUser() {
const id = sessionStorage.getItem('userId');
this.userService.findUserById(+id).subscribe(response => {
this.user = response;
console.log(this.user);
});
}
tweet: Tweet = new Tweet();
createTweet() {
this.tweet.message = this.tweetForm.get('text').value;
this.tweetService.createTweet(this.tweet).subscribe(response => {
this.tweet = response;
this.tweet.user = this.user;
});
}
Solution
createTweet(): Observable<yourTypeHere> {
this.tweet.message = this.tweetForm.get('text').value;
return this.tweetService.createTweet(this.tweet);
}
getUser() {
const id = sessionStorage.getItem('userId');
this.userService.findUserById(+id).pipe(
tap((response) => this.user = response),
switchMap(() => this.createTweet())
)
.subscribe((tweetResponse) => {
this.tweet = response;
this.tweet.user = this.user;
});
}
Or using forkJoin
:
createTweet(): Observable<yourTypeHere> {
this.tweet.message = this.tweetForm.get('text').value;
return this.tweetService.createTweet(this.tweet);
}
getUser(): Observable<anotherTypeHere> {
this.tweet.message = this.tweetForm.get('text').value;
return this.tweetService.createTweet(this.tweet);
}
someFunction(): void {
const myUserAndTweet = forkJoin({
user: this.getUser(),
tweet: this.createTweet()
});
myUserAndTweet.subscribe(values => {
this.user = values.user;
this.tweet = values.tweet;
this.tweet.user = this.user;
});
}
Answered By - Andres2142
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.