gpt4 book ai didi

javascript - 将响应映射到模型对象

转载 作者:行者123 更新时间:2023-12-03 02:10:27 26 4
gpt4 key购买 nike

我正在尝试将 GET 调用的响应映射到我的对象,该对象的属性与 JSON 对象的属性为 1:1。这是我的代码:

线程模型:

export class Thread {
private source: Source;
private target: Target;
private messages: Message[];

constructor(data) {
this.source = data.source;
this.target = data.target;
this.messages = data.messages;
}

sum() {
return 'Hello from Thread';
}
}

线程服务:

@Injectable()
export class ThreadService {
constructor(private http: HttpClient) {
}
getAll(): Observable<Thread[]> {
return this.http.get<Thread[]>('/api/thread').map(value => new Thread(value))
}
}

ThreadService 中的 getAll 方法给出以下错误:

src/app/service/thread.service.ts(13,5): error TS2322: Type 'Observable<Thread>' is not assignable to type 'Observable<Thread[]>'. Type 'Thread' is not assignable to type 'Thread[]'. Property 'includes' is missing in type 'Thread'.

您能告诉我将响应映射到模型的正确方法是什么吗?这允许我在该模型中调用自定义方法?我读过一些有关拦截器的内容,但我找不到任何示例。感谢您的帮助。

最佳答案

@Injectable()
export class ThreadService {
constructor(private http: HttpClient) {
}
getAll(): Observable<Thread[]> {
return this.http.get<Thread[]>('/api/thread').map(threads=> threads.map(thread => new Thread(thread)))
}
}

关于javascript - 将响应映射到模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49598098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com