我收到错误
致命错误:未找到 LoginResponse 类型的 ObservableObject。LoginResponse 的 View.environmentObject(_:) 作为该视图的祖先可能会丢失。
我已将环境对象传递给 LoginView() 的所有子视图,但错误仍然存在
struct LoginView: View {
@State var loginCredentials = Credentials()
var loginResponse = LoginResponse()
var dataCall = DataCall()
var body: some View {
VStack{
Button(action:{self.dataCall.AttemptLogin(loginCredentials: self.loginCredentials)}){
Text("LOGIN")
}
Text("\(self.loginResponse.jwt)")
}
.environmentObject(self.loginResponse)
.padding(.horizontal)
}
}
如果需要,这是其余的代码
struct Credentials: Encodable {
var login: String = ""
var password: String = ""
}
class LoginResponse: Decodable, ObservableObject {
enum CodingKeys: CodingKey {
case success, userId, jwt
}
@Published var success: Bool = false
@Published var userId: String = ""
var error: String = ""
@Published var jwt: String = ""
init(){}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
success = try values.decode(Bool.self, forKey: .success)
userId = try values.decode(String.self, forKey: .userId)
jwt = try values.decode(String.self, forKey: .jwt)
}
}
struct DataCall {
@EnvironmentObject var dataResponse : LoginResponse
func AttemptLogin(loginCredentials: Credentials) {
let loginResponse = LoginResponse()
dataResponse.success = loginResponse.success
}
}