Inject() 函数在 Angular 中创建不需要的新实例

问题描述 投票:0回答:2

我只是想确认

inject()
提供了不同的服务实例,这就是我的代码无法工作的原因。

仔细看看下面的代码:

{
        path: 'recipes',
        component: RecipesComponent,
        resolve: {data: () => inject(HttpService).fetchRecipes()},
        children: [
           // a bunch of child routes 
        ]
},

现在,当我们使用

inject(HttpService)
时,我会假设该实例不是全局应用程序范围的,或者换句话说,它不在根目录中。请查看 Http 服务。

@Injectable({
    providedIn: 'root'
})
export class HttpService {
    constructor(private recipeService: RecipeService, private http: HttpClient, private authSerivce: AuthService) {}
    storeRecipes() {
        const recipes = this.recipeService.getRecipes()
        this.http.put('https://ng-recipe-shopping-f9c65-default-rtdb.firebaseio.com/recipes.json', recipes)
        .subscribe(respone => {
            console.log(respone)
        })
    }

    ngOnInIt() {

    }

    fetchRecipes() {
        let authId: string
        this.authSerivce.userCred.subscribe(authToken => {
            authId = authToken
        })
      return  this.http.get<Recipe[]>(`https://ng-recipe-shopping-f9c65-default-rtdb.firebaseio.com/recipes.json?auth=${authId}`)
        .pipe(map(recipes => {
            return recipes.map(recipe => {
                
                return {
                    ...recipe,
                    ingredients: recipe.ingredients ? recipe.ingredients : []
                }
            })
        }),
        tap(recipes => {
            this.recipeService.fetchRecipes(recipes)
        }))
    }
}

现在我假设当我在路由模块中调用

fetchRecipes()
方法时,我没有在根实例上调用
fetchRecipes()
。我之所以声明这一事实,是因为即使我在应用程序的其他地方调用
userCred
userCred.next(/* value */)
订阅也不会运行。如果订阅无法运行的原因是因为存在不同的
HttpService
实例,那么我想知道如何解决它。

请记住,我对 Angular 还比较陌生,并且我从官方文档中了解了 60% 的依赖注入上下文,但我仍然找不到我想要的东西。

提前致谢:)

angular typescript
2个回答
0
投票

当您在类中使用

Injectable
装饰器并将
providedIn
属性设置为
'root'
时,Angular 会将此类视为单例,因此只会创建和使用它的单个实例。

userCred
订阅未捕获流发射一定是由于其他问题。


0
投票

让我们先调整你的 fetchRecipes 函数。

fetchRecipes() {
    return this.authSerivce.userCred.pipe(
        switchMap(authToken => {
            return this.http.get<Recipe[]>(`https://ng-recipe-shopping-f9c65-default-rtdb.firebaseio.com/recipes.json?auth=${authToken}`)
        }),
        map(recipes => {
           return recipes.map(recipe => {      
               return {
                   ...recipe,
                   ingredients: recipe.ingredients ? recipe.ingredients : []
               }
           })
       }),
       tap(recipes => {
           this.recipeService.fetchRecipes(recipes)
       }))
}

这样,您实际上将使用 userCred 令牌,现在它是一个单独的订阅,根据我从您的代码中读取的内容,该订阅将不起作用。

© www.soinside.com 2019 - 2024. All rights reserved.