Skip to content

Instantly share code, notes, and snippets.

@sp90
Last active April 11, 2023 21:38
Show Gist options
  • Save sp90/b562f624a37bb977bcc610d63dce8315 to your computer and use it in GitHub Desktop.
Save sp90/b562f624a37bb977bcc610d63dce8315 to your computer and use it in GitHub Desktop.
How i would use angular
<pre>{{ user$ | async | json }}</pre>
import { UserState } from '@states/user/user.state'
@Component({
selector: 'app-user-icon',
templateUrl: './user-icon.component.html',
styleUrls: ['./user-icon.component.scss'],
imports: [CommonModule],
standalone: true
})
export class UserIconComponent {
user$ = this.userState.user$;
constructor(private userState: UserState) {}
}
import { HttpClient } from '@angular/common/http';
export interface User {
name: string;
foo: number;
}
interface UserResponse {
message: string;
user: {
name: string;
hello: {
foo: number;
}
}
}
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private http: HttpClient) {}
// Get data through http, graphql or what ever floats your boat
// Map data to fit the application
getMyUser(): User {
this.http.get<UserResponse>('SOME_URL').pipe(take(1), map((res) => {
return {
name: res.user.name,
foo: res.user.hello.foo
}
}))
}
}
import { User, UserService } from '@services/user/user.service'
@Injectable({
providedIn: 'root'
})
export class UserState {
private userSource = new BehaviourSubject<User | null>(null);
user$ = this.userSource.asObservable();
constructor(private userService: UserService) {}
// This can be done in various ways i tend to either call something like this
// Or have a functional guard if i want to use params, queryParams or the likes because then i dont listen for changes i just take them from the url
loadUser() {
this.userService.getMyUser()
.pipe(
tap((user) => this.userSource.next(user))
),
.subscribe()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment