PageContext in SharePoint Framework
Вопрос
We all know that _spPageContextInfo
is a very useful thing in Client side development. I need something equivalent of _spPageContextInfo
in SPFX. Currently I am unable to use it directly from typescript. It gives error like
Can not find '_spPageContextInfo'
Finally, I have gone through the API documentation of SharePoint Framework and found PageContext. PageContext
has dependence with ServiceScope. My qestion is: How to use PageContext
? I need to use it my BaseService
class. constructor
of my class is:
constructor(private $http: ng.IHttpService, private $q: ng.IQService, serviceScope: ServiceScope) {
serviceScope.whenFinished(() => {
this.pageContext = new PageContext(serviceScope);
console.log(this.pageContext);
});
}
Inside the constructor
serviceScope
is undefined
. I know the reason: As I am not injecting/initialising serviceScope
anywhere like other angular services. So what is the approach of injecting/initialising serviceScope
in angular service class?
Решение
Enjoyed reading the comments on this one (all good points, and I will add the level of abstraction it adds when you are trying to debug!) :-) Anyway, I believe this is what you are looking for*:
//import { IWebPartContext } from '@microsoft/sp-client-preview'; // Old dcumentation refers to this.
import { IWebPartContext} from '@microsoft/sp-webpart-base';
And then you can do (*assume the context has the stuff you are looking for in):
public context: IWebPartContext;
And then, for example:
url = this.context.pageContext.web.absoluteUrl + "/_api/web/lists/GetByTitle('SomeList')/
Другие советы
We are in the process of mapping the various properties on spPageContextInfo into a well typed collection of objects that will hang off the context. The start of this is accessible via this.context.pageContext in your webpart code.
Also - OnInit might be a better place to put initialization code rather than the constructor.