I am facing an issue where I need to use the value from the user outside the subscribe function in order to assign it to my tweet class. However, when I try to print it outside the subscribe function, it shows as undefined. Can anyone provide a solution for this?
Below is my code snippet:
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;
});
}