我正在从 Nuxt3 中的 API 获取数据。我正在使用打字稿,我希望定义我将获得的数据类型。我如何指定这一点?
<script lang="ts" setup>
interface APIBody {
/* properties defined here */
}
const {data} = await useFetch("api_url here")
</script>
<template>
{{ data.name.officialName }}
<template>
Run Code Online (Sandbox Code Playgroud)
template我在显示的位置出现错误data.name.officialName
属性“name”在类型“never”上不存在
但是,在浏览器中运行代码时,该网站运行良好。
编辑 我尝试了以下代码,但现在收到不同的错误。
<script lang="ts" setup>
interface APIBody {
/* properties defined here */
}
const typedData = ref<APIBody[]>()
const {data} = await useFetch("api_url here")
typedData.value = data as APIBody[] // -> error here
</script>
<template>
{{ data.name.officialName }}
<template>
Run Code Online (Sandbox Code Playgroud)
本例中的错误是:
将类型“Ref<Pick<unknown, never>>”转换为类型“APIBody[]”可能是一个错误,因为两种类型都没有与另一种类型充分重叠。
在我的 ViewModel 中,我正在发出 API 请求,并且正在使用 FragmentStateFlow并SharedFlow与 Fragment 进行通信。在发出 API 请求时,我可以轻松更新状态流的值,并将其成功收集到片段中。
但在发出请求之前,我发出了一些布尔值,SharedFlow并且它没有被收集在片段中。有人可以帮助我为什么会发生这种情况吗?
class MainViewModel: ViewModel() {
private val _stateFlow = MutableStateFlow(emptyList<Model>())
val stateFlow = _stateFlow.asStateFlow()
private val _loading = MutableSharedFlow<Boolean>()
val loading = _loading.asSharedFlow()
suspend fun request() {
_loading.emit(true)
withContext(Dispatchers.IO) {
/* makes API request */
/* updates _stateFlow.value */
/* stateFlow value is successfully collected */
}
_loading.emit(false) // emitting boolean value
}
}
Run Code Online (Sandbox Code Playgroud)
class MyFragment : Fragment(R.layout.fragment_my) {
// ...
override …Run Code Online (Sandbox Code Playgroud) android kotlin kotlin-coroutines kotlin-flow kotlin-sharedflow