Within my component, I have a scenario where an object is generated from this.route.snapshot
.
This object is received by the component through a resolver.
In one case, the resolver provides an object with data.
But in another case, the resolver returns an object where all properties are empty.
The issue arises in this second case.
I find myself needing to manually set each property value, like so:
return of({personId: '', firstName: '', lastName: ''});
However, I am looking for a more streamlined approach without having to declare every property individually.
Something along the lines of:
return new Observable<Person>;
Unfortunately, this method does not succeed.
I wish to simplify this process because there are instances where I need to return objects with numerous properties. Some of these properties may be complex objects or arrays, not just simple strings that can be initialized as empty values. Thus, I am forced to painstakingly create each object and set its properties, sometimes referencing other objects, in order to make the return possible. Take a look at the code snippet below to see what I mean. I was curious if there exists a more straightforward way to return a clean object.
person.ts
export interface Person {
personId: string;
firstName: string;
lastName: string;
group: Group;
}
person.component.ts
...
ngOnInit(): void {
const person: Person = this.route.snapshot.data['person'];
...
person.resolver.ts
@Injectable({
providedIn: 'root'
})
export class PersonResolver implements Resolve<Person> {
constructor(private service: PersonsService){ }
personGroup: PersonGroup = {groupId: '', groupName: ''...}
resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<Person> {
return of({personId: '', firstName: '', lastName: '', group: this.personGroup, ...});
}
}
Here are some alternative approaches I've tested:
return null;
Error Message: Type 'null' is not assignable to type 'Observable'
let person = {} as Person;
return person;
Error Message: Type 'Person' is missing essential properties such as _isScalar, source, operator, lift, and more.
return new Observable<Person>;
No error occurs, but it fails to return to the ngOnInit() function in component.ts to continue executing.
let person: Partial<Person> = {};
return person;
Error Message: Type 'Partial' is missing key properties required by 'Observable': _isScalar, source, operator, lift, and more.
let person: Person | Record<string, never> = {};
return person;
Error Message: Type 'Record<string, never>' lacks necessary properties like _isScalar, source, operator, lift, and more needed for 'Observable'.