6

我有一个 LoginView,如果用户未登录,则显示 RegisterView,如果用户已登录,则显示 ContentView:

struct LoginView: View {
    @EnvironmentObject var userManager: UserManager
    var body: some View {
        Group {
            if userManager.isRegistered {
                ContentView()
            } else {
                RegisterView()
            }
        }
    }
}

ContentView具有三个ObservedObject属性,它们使用 combine 从带有 rest api 的服务器获取内容。

struct ContentView: View {
    @EnvironmentObject var userManager: UserManager
    @ObservedObject var usersStore = UsersStore()
    @ObservedObject var rolesStore = RolesStore()
    @ObservedObject var elementsStore = ElementsStore()

    var body: some View {
        NavigationView {
            ZStack {
                Image("stell")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .opacity(0.1)

                VStack(alignment: .leading, spacing: 5) {
                    NavigationLink(destination: UsersView(usersStore: usersStore) ) {
                        Text("Users")
                    }
                    NavigationLink(destination: RolesView(rolesStore: rolesStore)) {
                        Text("Roles")
                    }
                    NavigationLink(destination: ElementsView(elements: $elementsStore.elements)) {
                        Text("Elements")
                    }
                }.font(.title).padding(20)
            }.navigationBarTitle(Text("STELL"))
        }
    }
}

我遇到的问题是我想从任何observedObjects 中引用,例如当会话令牌过期userManager时其余api 返回时。401 Unauthorized然后我希望 ObservedObject 将isRegistered标志设置为userManagerfalse以便RegisterView自动显示。但我该怎么做呢?我无法userManager在任何 ObservedObject 属性初始化程序中设置对的引用,因为编译器抱怨属性初始化程序在self可用之前运行。

4

1 回答 1

8

在这种情况下,我将通过构造函数使用依赖注入...下面显示了示例的可能方法UsersStore,对于其他示例,它是相同的

改变在UsersStore

class UsersStore: ObservableObject {
    var manager: UserManager

    init(manager: UserManager) { // << inject UserManager via constructor
        self.manager = manager 
    }
    ...
}

改变在ContentView

struct ContentView: View {
    @EnvironmentObject var userManager: UserManager
    @ObservedObject var usersStore: UsersStore

    init(usersStore: UsersStore) {
        self.usersStore = usersStore // << inject UsersStore via contructor
    }

使用方式的变化

struct LoginView: View {
    @EnvironmentObject var userManager: UserManager
    var body: some View {
        Group {
            if userManager.isRegistered {
                // userManager is valid here some UsersStore can be created
                ContentView(usersStore: UsersStore(manager: self.userManager))
于 2020-02-01T17:49:58.023 回答