簡體   English   中英

如何將環境 Object 傳遞給我的 ViewModel SwiftUI

[英]How do I pass in an Environment Object to my ViewModel SwiftUI

我正在使用 function 通過 API 端點從數據庫中獲取食譜。 它接受 3 個參數,脂肪、碳水化合物、蛋白質,我希望這些值等於我的環境 object(或兩個環境對象的計算)fatGoal - fatProgress 等。但是在我的 viewModel 中,嘗試使用時出現以下錯誤我的環境 object:

Thread 1: Fatal error: No ObservableObject of type UserInfoModel found. A View.environmentObject(_:) for UserInfoModel may be missing as an ancestor of this view.

這是我的 ViewModel 服務文件:

import SwiftUI
import Combine
import Foundation

class MealViewModel: ObservableObject {
    
    @Published var nutrients: [RecipieAPI] = []
    
    @EnvironmentObject var person: UserInfoModel
    
    
    @State public var fat = 0
    @State public var carbs = 0
    @State public var protein = 0


    
    init() {
        
        fetchNutrients()


    }
    
    func fetchNutrients() {
        NetworkServices.fetchNutrients(maxProtein: self.person.recipeNutrientsSearch.protein , maxFat: self.person.recipeNutrientsSearch.fat,  maxCarbs: self.person.recipeNutrientsSearch.carb, number: 4) { (nutrients, error) in
            if let error = error {
                print(error)
            } else {
                if let nutrientList = nutrients as? [RecipieAPI] {
                    self.nutrients = nutrientList
                }
            }
        }
    }
}

錯誤被調用

NetworkServices.fetchNutrients(maxProtein: self.person.recipeNutrientsSearch.protein , maxFat: self.person.recipeNutrientsSearch.fat,  maxCarbs: self.person.recipeNutrientsSearch.carb, number: 4) { (nutrients, error) in

任何幫助將不勝感激

編輯內容視圖:

import SwiftUI

struct ContentView: View {

    
    //Instantiating an object of UserInfo Model (referenced in App.swift too 
    @EnvironmentObject var person: UserInfoModel
    

    
    init() {
        //Setting appearance of UI colour
        UITabBar.appearance().backgroundColor = ColourManager.UIColour1
    }
    
    var body: some View {
        
        
        TabView {
            ProfileView().tabItem ({
                Text("Profile")
            }).tag(0)
            
            TrackerView().tabItem ({
                Text("Tracker")
            }
            ).tag(1)

            
            AddView().tabItem ({
                Text("Add")
            }).tag(2)
            
            MealView().tabItem ({
                Text("Meals")
            }).tag(3)
        }.accentColor(ColourManager.Colour3)
        .environmentObject(UserInfoModel())

        
        }

    }

環境 Object class:用戶信息型號:

import Foundation

class UserInfoModel: ObservableObject {
    
    
    struct UserInfo: Identifiable {
        var id = UUID()
        var firstName: String
        var height: Double
        var weight: Double
        var gender: String
        var age: Double
        var activityLevel: String
        var BMR: Double
        
    }
    
    struct AddedFoods:Identifiable{
        var name: String = ""
        var totalCals: Double = 0
        var totalProtein: Double = 0
        var totalCarbs: Double = 0
        var totalFat: Double = 0
        var id = UUID().uuidString
       //Your other properties
    }
    
    struct DailyCalorieGoals: Identifiable{
        var id = UUID()
        var calorieGoal: Double
        var fatGoal: Double
        var proteinGoal: Double
        var carbGoal: Double

    }
    
    struct CurrentCalorieProgress: Identifiable{
        var id = UUID()
        var calorieProgress: Double
        var fatProgress: Double
        var carbProgress: Double
        var proteinProgress: Double

    }
    
    struct SearchRecipeCalories: Identifiable{
        var id = UUID()
        var fat: Int
        var carb: Int
        var protein: Int

    }
    
    @Published var personUserInfo = UserInfo.init(firstName: "",  height: 0, weight: 0, gender: "", age: 0, activityLevel: "", BMR: 0)
    @Published var personDailyCalorieGoals = DailyCalorieGoals.init(calorieGoal: 2400, fatGoal: 40, proteinGoal: 40, carbGoal: 40)
    @Published var personCurrentCalorieProgress = CurrentCalorieProgress.init(calorieProgress: 1200, fatProgress:   12, carbProgress: 5, proteinProgress: 30)
    
    @Published var  recipeNutrientsSearch = SearchRecipeCalories.init(fat: 0, carb: 0, protein: 0)
    
    
}

EnvironmentObjects 必須由祖先視圖提供!


 import SwiftUI
    
    @main
    struct pro2App: App {    // <<: Here: your app name!
        var body: some Scene {
            WindowGroup {
                ContentView()
                    .environmentObject(MealViewModel()) // <<: Here!
                    .environmentObject(UserInfoModel.shared) // <<: Here!
            }
        }

}

    class MealViewModel: ObservableObject {
    
    @Published var nutrients: [RecipieAPI] = []
    
    let person: UserInfoModel.shared   // <<: Here
    
    
    @State public var fat = 0
    @State public var carbs = 0
    @State public var protein = 0


    
    init() {
        
        fetchNutrients()


    }
    
    func fetchNutrients() {
        NetworkServices.fetchNutrients(maxProtein: self.person.recipeNutrientsSearch.protein , maxFat: self.person.recipeNutrientsSearch.fat,  maxCarbs: self.person.recipeNutrientsSearch.carb, number: 4) { (nutrients, error) in
            if let error = error {
                print(error)
            } else {
                if let nutrientList = nutrients as? [RecipieAPI] {
                    self.nutrients = nutrientList
                }
            }
        }
    }
}

class UserInfoModel: ObservableObject {
    
static let shared: UserInfoModel = UserInfoModel() // <<: Here
    
    struct UserInfo: Identifiable {
        var id = UUID()
        var firstName: String
        var height: Double
        var weight: Double
        var gender: String
        var age: Double
        var activityLevel: String
        var BMR: Double
        
    }
    
    struct AddedFoods:Identifiable{
        var name: String = ""
        var totalCals: Double = 0
        var totalProtein: Double = 0
        var totalCarbs: Double = 0
        var totalFat: Double = 0
        var id = UUID().uuidString
       //Your other properties
    }
    
    struct DailyCalorieGoals: Identifiable{
        var id = UUID()
        var calorieGoal: Double
        var fatGoal: Double
        var proteinGoal: Double
        var carbGoal: Double

    }
    
    struct CurrentCalorieProgress: Identifiable{
        var id = UUID()
        var calorieProgress: Double
        var fatProgress: Double
        var carbProgress: Double
        var proteinProgress: Double

    }
    
    struct SearchRecipeCalories: Identifiable{
        var id = UUID()
        var fat: Int
        var carb: Int
        var protein: Int

    }
    
    @Published var personUserInfo = UserInfo.init(firstName: "",  height: 0, weight: 0, gender: "", age: 0, activityLevel: "", BMR: 0)
    @Published var personDailyCalorieGoals = DailyCalorieGoals.init(calorieGoal: 2400, fatGoal: 40, proteinGoal: 40, carbGoal: 40)
    @Published var personCurrentCalorieProgress = CurrentCalorieProgress.init(calorieProgress: 1200, fatProgress:   12, carbProgress: 5, proteinProgress: 30)
    
    @Published var  recipeNutrientsSearch = SearchRecipeCalories.init(fat: 0, carb: 0, protein: 0)
    
    
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM